如何在集合中找到低于关键字的数字?C++

How to find number lower than key in set? C++

本文关键字:关键字 数字 C++ 集合      更新时间:2024-09-29

我是C++世界的新手。集合中有一个upper_bound函数,它返回的数字大于传递的值。我想知道是否有任何方法可以得到一个低于传递值的数字?假设我们在集合中有{3,6,8,9,11},通过传递给我的函数:func(8(,我将得到6,因为6是在8之前的数字。知道吗?

您的方法是合理的,但您应该使用std::lower_bound而不是std::upper_bound,例如:

#include <iostream>
#include <set>
using namespace std;
int main(void)
{
set<int> myset{3, 6, 8, 9, 11};
set<int>::iterator it = myset.lower_bound(8);
if (it != myset.begin()) {
it--;
cout << *it << endl;
} else {
cout << "No smaller element found!" << endl;
}
return 0;
}

Ouptut:

6