检查STL排序向量中upper_bound的返回值

时间:2012-11-02 10:14:11

标签: 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;
}

我在上面有以下输出

  

位置5的lower_bound位于第7位的upper_bound按任意键   继续。

我的问题是如何在上面的情况下检查上限返回值没有超过20的值?

谢谢!

2 个答案:

答案 0 :(得分:1)

auto up = upper_bound(v.begin(), v.end(), 20);

cout<<*up<<endl; //dereference iterator and you will get a value

检查迭代器是否有效将其与end()迭代器进行比较:

if (up == v.end()) {
    //no upper bound
} 

答案 1 :(得分:1)

您只需要检查上限的迭代器是否等于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/