c++ - 检查 STL 排序 vector 中 upper_bound 的返回值

标签 c++ stl

我有以下程序

int main()
{
    int myints[] = {1, 2, 3, 3, 4, 6, 7};
    vector<int> v(myints,myints+7);
    vector<int>::iterator low,up;

    sort (v.begin(), v.end());

    low=lower_bound (v.begin(), v.end(), 5);          ^
    up= upper_bound (v.begin(), v.end(), 20);                   ^

    cout << "lower_bound at position " << int(low- v.begin()) << endl;
    cout << "upper_bound at position " << int(up - v.begin()) << endl;

    return 0;
}

上面我有以下输出

lower_bound at position 5 upper_bound at position 7 Press any key to continue . . .

我的问题是,在上述情况下,如何检查返回值的上限,没有大于 20 的值?

谢谢!

最佳答案

你只需要检查上限的迭代器是否等于 v.end():

if (up == v.end())
    // there is no value greater than your upper bound

有关 upper_bound 的更多信息,请参阅:http://www.cplusplus.com/reference/algorithm/upper_bound/

关于c++ - 检查 STL 排序 vector 中 upper_bound 的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13193236/

相关文章:

c++ - std::queue<T, list<T>>::size() 在 O(n) 中很慢?

c++ - STL Vector和模板函数问题

c++ - 在静态库中包含静态库 - CodeBlocks

c++ - 我如何知道 USB 设备是否已在使用中?

c++ - 将 Delphi 类传递给需要具有 __thiscall 方法的类的 C++ 函数/方法

C++ std::destroy(T * 指针)

c++ - 在哪里可以找到有关 "int C::*"用法的说明?

c++ - C/C++ 条件返回语句

c++ - 如何在MFC对话框应用程序中将复选框设置为默认选中?

c++ - 如何为 const 模板参数定义复制构造函数?