如何将 std::lower_bound 与 std::map 一起使用?

How to use `std::lower_bound` with `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

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

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