简体   繁体   中英

Using std::lower_bound with std::vector::const_iterator

I'm trying to find bounds in the part of vector from next iterator position to the end of the vector.

The code is:

#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;
}

Unfortunately, std::lower_bound(i+1, v.end(), -10-*i) triggers compilation error which I cannot understand:

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...
^

What is the problem with the statement above and how to properly call std::lower_bound with i+1 iterator?

The error probably says that it can't deduce the template argument - i is const_iterator while v.end() returns iterator . This should do the trick:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM