Lower_bound strange output

Hello, quick question here. I have this code snippet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <deque>
#include <iostream>
#include <algorithm>

using namespace std;

void printer(int i)
{
        cout << i << ", ";
}
int main()
{
        int mynumbers[] = { 3, 9, 0, 2, 1, 4, 5 };
        deque<int> d1(mynumbers, mynumbers + 7);
        deque<int>::iterator it = lower_bound(d1.begin(), d1.end(), 3);
        d1.push_back(6);
        for_each(it, d1.end(), printer);
        return 0;
}


It always outputs "4, 5, 6" and I am wondering why it is not the whole range - the first value matches the searched one.
I know a container should be sorted before performing search operations, but I was unable to find if there is any predictability at all (implied by same result when the code snippet is run) when searching a non sorted container.

Last edited on
¿why do you consider your output to be strange then?
gigo
Lower bound is meant to return an element greater than or equal to given value in a given range. I am searching for '3' but an iterator to '4' is returned, despite 3 existing in d1.

I think I found my answer nevertheless in that the first element to be checked is in the middle of the range ('2') and then it searches towards the back, which then makes sense to pick '4'.
The container being sorted or at least partitioned is a pre-condition for using std::lower_bound


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <deque>
#include <iostream>
#include <algorithm>

using namespace std;

void printer(int i)
{
        cout << i << ", ";
}
int main()
{
        int mynumbers[] = { 3, 9, 0, 2, 1, 4, 5 };
        sort(mynumbers, mynumbers + 7);
        deque<int> d1(mynumbers, mynumbers + 7);
        deque<int>::iterator it = lower_bound(d1.begin(), d1.end(), 3);
        d1.push_back(6);
        for_each(it, d1.end(), printer);
        return 0;
}


 3, 4, 5, 9, 6, 


What you got is undefined behavior, as the precondition was violated.
Topic archived. No new replies allowed.