c++stdmaplower-boundupperbound

How to use `std::lower_bound` with `std::map`?


I have this question:

I have a std::map of strings to integers representing list of fruits:

map<string, int> fruits{
    {"Apple", 5}, {"Grapefruit", 7}, {"Cherry", 10}, {"Grapes", 16}
};


for (const auto& p : fruits)
    cout << p.first << " " << p.second << endl;
cout << endl << endl;


auto it = fruits.begin();
++++it;

using type = std::pair<class std::basic_string<char, struct std::char_traits<char>, class std::allocator<char> > const, int>;

auto it2 = std::lower_bound(fruits.cbegin(), fruits.cend(), type{"Cherry", 10});
//  auto it3 = std::lower_bound(fruits.cbegin(), fruits.cend(), pair<string, int>{ "Cherry", 10 });
auto it4 = std::lower_bound(fruits.cbegin(), fruits.cend(), pair<const string, int>{ "Cherry", 10 });

for (auto beg = fruits.cbegin(); beg != it2; ++beg)
    cout << beg->first << " " << beg->second << endl;

cout << typeid(*it).name() << endl;

So my problem was How to pass the third parameter to std::lower_bound explicitly?


Solution

  • Don't do that. std::map has its own member function lower_bound so that you don't need a comparison function, and it's more efficient too.

    An iterator to map has the first part const because you can't change it. The data types and algorithms used rely on the key value remaining the same over the life of the map.