unexpected output from C++ multiset lower_bound

360 views Asked by At

Wondeirng why below code returns 1? I never insert 1 into the multiset container.

#include <iostream>
#include <set>

int main ()
{
  std::multiset<int> mymultiset;
  std::multiset<int>::iterator itlow;

  mymultiset.insert(-3);
  itlow = mymultiset.lower_bound (3);
  std::cout << *itlow << endl; // output 1

  return 0;
}
3

There are 3 answers

1
Pete Becker On BEST ANSWER

mymultiset.lower_bound(3) returns the lowest location in the container where 3 could go, and that's at the end of the container. So itlow is equal to mymultiset.end(), and it is not dereferenceable. std::cout << *itlow has undefined behavior.

0
Yinon On

You are trying to get an Iterator which his lower bound is 3, and your maximum value is -3. So you've got an end iterator, which his value is undefined. You should use multiset::begin() as your Iterator, or put something like itlow = mymultiset.lower_bound (-4); which is not very gentle.

0
hago On

Hi to clarify my understanding I have one multiset which contains 1 and 5.

mset.insert(1);
mset.insert(5);
auto it = s.lower_bound(6);
cout<<*it<<endl;

Now, from the above answer, I will be getting 2 since that is the location where the value 6 can fit inside the container. Am I right?

Next, if I search for the value 4, I am getting 5. Here I don't think the iterator has reached the mset.end(). Am I right?

Thanks