lower_bound 和 upper_bound 的区别

std::lower_bound

  • 作用: 返回第一个 大于等于 (>=) 指定值的元素的迭代器。
  • 如果值存在: 返回该值的第一个位置。
  • 如果值不存在: 返回比目标值 大的第一个元素 位置。
  • 如果所有元素都小于目标值: 返回 end() 迭代器。
  • 反向查找小于目标值的元素std::lower_bound 返回的迭代器减一,即 std::lower_bound(vec.begin(), vec.end(), target) - 1

std::upper_bound

  • 作用: 返回第一个 大于 (>) 指定值的元素的迭代器。
  • 如果值存在: 跳过所有相同值,返回比目标值 大的第一个元素 位置。
  • 如果值不存在: 返回比目标值 大的第一个元素 位置。
  • 如果所有元素都小于等于目标值: 返回 end() 迭代器。
  • 反向查找小于等于目标值的元素std::upper_bound 返回的迭代器减一,即 std::upper_bound(vec.begin(), vec.end(), target) - 1
#include <algorithm>
#include<bits/stdc++.h>
using namespace std;
set<int> s;
void insertValue(int x){
    s.insert(x);
}
void eraseValue(int x){
    s.erase(x);
}
int xInSet(int x){
    auto i=s.find(x);
    if(i!=s.end()) return 1;
    else return 0;
}
int sizeOfSet(){
    return s.size();
}
int getPre(int x){
    auto i=s.lower_bound(x);
    if(i==s.begin()) return -1;
    i--;
    return *i;
}
int getBack(int x){
    auto i=s.upper_bound(x);
    if(i==s.end()) return -1;
    return *i;
}