首页 > 解决方案 > 如何将`std::lower_bound`与`std::map`一起使用?

问题描述

我有这个问题:

我有一个std::map代表水果列表的整数字符串:

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;

所以我的问题是如何将第三个参数std::lower_bound显式传递给?

标签: c++stdmaplower-boundupperbound

解决方案


不要那样做。 std::map有自己的成员函数lower_bound,不需要比较函数,效率也更高。

一个迭代器map拥有该first部分const,因为您无法更改它。使用的数据类型和算法依赖于在地图生命周期内保持不变的键值。


推荐阅读