简体   繁体   中英

c++11 reverse iterator and lower_bound

I have the following example program:

#include <iostream>
#include <string>
#include <map>

int main()
{
  std::map<int, int> a;
  a[8] = 1;
  a[5] = 1;
  a[1] = 1;
  a[2] = 1;

  std::cout << a.begin()->first << std::endl;

  std::cout << a.rbegin()->first << std::endl;
  std::cout << (++a.rbegin())->first << std::endl;
  std::cout << (--a.rbegin())->first << std::endl;

  std::cout << (a.lower_bound(6))->first << std::endl;
}

When I execute it I get this output:

1
8
5
5
8

I have two questions. The first is why ++a.rbegin() and --a.rbegin() iterate in the same direction? Is the iterator returned from a.rbegin() not a bidirectional iterator?

The second question is why does a.lower_bound(6)->first return 8 instead of 5? Based on https://en.cppreference.com/w/cpp/container/map/lower_bound , it should return an iterator to the first element "not less than key". So I would have thought 5 would be returned since 8 > 6.

--a.rbegin() is a UB.

lower_bound(val) returns an iterator pointing to the first element in the range which does not compare less than val . 5 is not "not less than 6 " so you get the iterator to 8 correctly

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