将std :: lower_bound与std :: vector :: const_iterator一起使用

时间:2015-02-24 11:10:11

标签: c++ c++11 stdvector

我试图在向量的一部分中找到从下一个迭代器位置到向量末尾的边界。

代码是:

#include <algorithm>
#include <vector>
#include <iostream>

int
main()
{
    typedef std::vector<int> Vector;

    Vector v;
    v.push_back(3);
    v.push_back(7);
    v.push_back(15);
    v.push_back(21);
    std::sort(v.begin(), v.end());
    for (Vector::const_iterator i = v.begin(); i != v.end(); ++i) {
        Vector::const_iterator low = std::lower_bound(i+1, v.end(), -10-*i);
        Vector::const_iterator high = std::upper_bound(i+1, v.end(), 10-*i);
        for (Vector::const_iterator j = low; j != high; ++j) {
            std::cout << *i << "~" << *j << std::endl;
        }
    }
    return 0;
}

不幸的是,std::lower_bound(i+1, v.end(), -10-*i)触发了我无法理解的编译错误:

c++ -O3 -ggdb -std=c++11 -W -Wall -pedantic -Wl,-stack_size -Wl,0x1000000    2sum.cc   -o 2sum
2sum.cc:26:26: error: no matching function for call to 'lower_bound'
                V::const_iterator lo = std::lower_bound(i+1, a.end(), -1...
                                       ^~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:4085:1: note:
      candidate template ignored: deduced conflicting types for parameter
      '_ForwardIterator' ('__wrap_iter<const long *>' vs.
      '__wrap_iter<long *>')
lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp...
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:4070:1: note:
      candidate function template not viable: requires 4 arguments, but 3 were
      provided
lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp...
^

上述声明有什么问题以及如何使用std::lower_bound迭代器正确调用i+1

1 个答案:

答案 0 :(得分:5)

错误可能表示它无法推断出模板参数 - iconst_iteratorv.end()返回iterator。这应该可以解决问题:

std::lower_bound( i+1, v.cend(), -10-*i);
                       ^^^^^^^^