// lower_bound/upper_bound example
#include <iostream> // std::cout
#include <algorithm> // std::lower_bound, std::upper_bound, std::sort
#include <vector> // std::vector
int main () {
int myints[] = {10,20,30,30,20,10,10,20};
std::vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20
std::sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30
std::vector<int>::iterator low,up;
low=std::lower_bound (v.begin(), v.end(), 20); // ^
up= std::upper_bound (v.begin(), v.end(), 20); // ^
std::cout << "lower_bound at position " << (low- v.begin()) << '\n';
std::cout << "upper_bound at position " << (up - v.begin()) << '\n';
return 0;
}
In this code can somebody please explain why we need to do (low - v.begin()) and (up - v.begin()) on the third and fourth lines from the bottom.
If I do
cout << low << endl;
I get the follwoing error which I dont understand
cannot bind ‘std::ostream {aka std::basic_ostream}’ lvalue to ‘std::basic_ostream&&’
*low *is an iterator as you declared. It holds the memory address that generates by your PC and you don't need any memory address to return . By writing
low- v.begin()
You make a command to your program to return the actual position of your searching query as an answer.
That's why it returns a value the
Address Position - Beginning of the Vector Position
Suppose your vector starting memory address is FFF1 and your searching value is at FFF8 ... Then it return FFF8 - FFF1 = 7 .. ( Example is just to illustrate )
That's how I understand .
The two subtractions are calculating the offset of the elements found at the positions low
and up
in the vector by calculating the delta between the iterator v.begin()
and the iterators low
and up
, respectively. To make this code clearer, it probably would have been better to use std::distance .
When you tried to use cout << low << endl;
you were trying to print out the value of the iterator. That's very different. Oh, and you're missing the std:: namespace reference around cout
and endl
.
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.