c++ - 如何将`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
显式传递给?
因为在得到帮助后,
typeid
我注意到这对first
是const
因为钥匙是constants
?如果我传递的给定键的值与容器中的键不匹配,也会发生什么情况。例如:带有键的元素
"Cherry"
有一个值,所以如果我使用无效的键传递给它10
,为什么可以正常工作?lower_bound
value
pair{"Cherry", 345}
该对的值是否传递给
lower_bound
任意值?
解决方案
不要那样做。 std::map
有自己的成员函数lower_bound
,不需要比较函数,效率也更高。
一个迭代器map
拥有该first
部分const
,因为您无法更改它。使用的数据类型和算法依赖于在地图生命周期内保持不变的键值。
推荐阅读
- sql-server - 如何每天在 SQL Server 中获取新插入的记录
- binary-tree - 二叉树修剪
- angular - 事件未显示在 Angular6 PRIMENG 调度程序中
- drupal - 评论失败时 Drupal 丢失了 CSS
- c# - 使用 lambda 选择从 DataTable 返回的前 1 行
- python - 通过在列中重复范围来分隔熊猫 df
- ios - 单个视图控制器的许多按钮
- wordpress - 函数 get_option() 不会从我的数据库中提取值
- c# - 实体框架多个 edmx 错误
- .net - 在 NServiceBus 5 中手动创建 InMemoryPersistence 订阅