Home:ALL Converter>std::lower_bound on std::vector with reverse iterators yields a wrong result

std::lower_bound on std::vector with reverse iterators yields a wrong result

Ask Time:2014-06-15T18:31:02         Author:rag3ous

Json Formatter

Recently I have came across a need to count elements that are outside of a given interval.

For example, if I have a sorted vector { 10, 20, 30 } and another sorted vector { 15, 25 }, whose boundaries define the interval. I want to count '10' and '30' (only 20 is inside the range). For this I use std::vector and std::lower_bound, once forward-scanning the vector, and once backward-scanning.

The code looks as following:

    int t[] = { 15, 25 };
int c[] = { 10, 20, 30 };

std::vector<int> tt(t, t + 2);
std::vector<int> cc(c, c + 3);

auto lower = std::lower_bound(cc.begin(), cc.end(), tt.front(), [](int a, int b){ return a < b; });
auto upper = std::lower_bound(cc.rbegin(), cc.rend(), tt.back(), [](int a, int b){ return a > b; });

size_t beforeCount = lower - cc.begin();
size_t afterCount = upper - cc.rbegin();

I expect both 'lower' and 'upper' to point to the same element: 20.

I've spent some time on this, does anyone see a problem here? I really want to use STL for that.

Thank you, Alex

Author:rag3ous,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/24228712/stdlower-bound-on-stdvector-with-reverse-iterators-yields-a-wrong-result
quantdev :

I think that you are confused between the difference of an iterator, and the value pointed-to by an iterator.\n\nYour program is doing exactly what you think, see it here.\n\nbeforeCount and afterCount are both equal to 1. They are iterators, not the value of any of your vector element, they are merely pointer to values in your vector.\n\nTo print the corresponding elements, simply do :\n\nstd::cout << cc[beforeCount] << std::endl;\nstd::cout << cc[afterCount] << std::endl;\n\n\nOutput:\n\n20\n\n20\n\nNote:\n\nYou can initialize your vector without the intermediate arrays:\n\nstd::vector<int> tt { 15, 25 };\nstd::vector<int> cc { 10, 20, 30 } ;\n",
2014-06-15T11:46:41
yy