跳到正文

个人记录

关于set和lower_bound的奇怪的事情

LiYomi约 3 分钟
原文
文章信息与版本

文章信息

发布
2022年11月30日
收录
2026年10月22日
更新
2026年11月18日
篇幅
约 3 分钟

版本

  1. v1当前
C++
set<int>s;
set<int>::iterator it1,it2;
it1=s.lower_bound();


// 重点来了
1. it2=it1-1; ×
2. it2=it1,it2--; √
只能自减,不然就会报iterator没有operator -错误

关于lower_bound()在set容器中超越了容器中的最大值,会返回的是end()而不是最大值的下标。关于这点

C++
// CPP program to demonstrate the 
// set::lower_bound() function 
#include <bits/stdc++.h> 
using namespace std; 
int main() 
{ 
  
    set<int> s; 
  
    // Function to insert elements 
    // in the set container 
    s.insert(1); 
    s.insert(2); 
    s.insert(4); 
    s.insert(5); 
    s.insert(6); 
  
    cout << "The set elements are: "; 
    for (auto it = s.begin(); it != s.end(); it++) 
        cout << *it << " "; 
  
    // when 2 is present 
    auto it = s.lower_bound(2); 
    cout << "\nThe lower bound of key 2 is "; 
    cout << (*it) << endl; 
  
    // when 3 is not present 
    // points to next greater after 3 
    it = s.lower_bound(3); 
    cout << "The lower bound of key 3 is "; 
    cout << (*it) << endl; 
  
    // when 8 exceeds the max element in set 
    it = lower_bound(s.begin(),s.end(),7);
    auto it2 = upper_bound(s.begin(),s.end(),7);
    //这里返回的是end(),如果要找到最大值还需要--;
//    if(it==s.end()) cout<<"?"<<endl;
//    cout << "The lower bound of key 8 is "; 
    cout << (*it) << endl; 
    cout << (*it2) << endl; 
  
    return 0; 
}
原文