[英]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
?
因为在从typeid
获得帮助后,我注意到这对的first
是const
是因为键是constants
吗?
如果我传递的给定键的值与容器中的键不匹配,也会发生什么情况。 例如:键为"Cherry"
的元素的值为10
,那么如果我使用键(如pair{"Cherry", 345}
传递给它的无效value
,为什么lower_bound
可以正常工作?
传递给lower_bound
的对的值是任意的吗?
不要那样做。 std::map
有自己的成员 function lower_bound
这样就不需要比较 function,效率也更高。
map
的迭代器具有first
部分const
因为您无法更改它。 使用的数据类型和算法依赖于在 map 的生命周期内保持不变的键值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.