如何将"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
?
因为在得到
typeid
的帮助后,我注意到这对first
const
这是因为钥匙constants
吗?如果我传递与容器中的键不匹配的给定键的值,会发生什么情况。 例如:带有键
"Cherry"
的元素有一个值10
那么如果我将无效value
传递给它,为什么lower_bound
正常工作,就像pair{"Cherry", 345}
一样?传递给
lower_bound
的货币对的值是任意的吗?
不要那样做。std::map
有自己的成员函数lower_bound
因此您不需要比较函数,而且效率也更高。
map
的迭代器具有const
first
部分,因为您无法更改它。 所使用的数据类型和算法依赖于在映射的生命周期内保持不变的键值。
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 使用一个考虑到std::map中键值的滚动或换行的键
- 如何从 std::atomic 中提取指针 T<T>?
- 为什么 std::unique 不调用 std::sort?
- 使用std::函数映射对象方法
- 如何检测我何时向可变参数函数传递"std::string"而不是"c_str()"