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

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

本文关键字:quot std 一起 map lower bound      更新时间:2023-10-16

我有这个问题:

我有一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

  • 因为在得到typeid的帮助后,我注意到这对firstconst这是因为钥匙constants吗?

  • 如果我传递与容器中的键不匹配的给定键的值,会发生什么情况。 例如:带有键"Cherry"的元素有一个值10那么如果我将无效value传递给它,为什么lower_bound正常工作,就像pair{"Cherry", 345}一样?

  • 传递给lower_bound的货币对的值是任意的吗?

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

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