Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何将'std::lower_bound'与'std::map'一起使用?_C++_Stdmap_Lower Bound_Upperbound - Fatal编程技术网

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

C++ 如何将'std::lower_bound'与'std::map'一起使用?,c++,stdmap,lower-bound,upperbound,C++,Stdmap,Lower Bound,Upperbound,我有一个问题: 我有一个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 &

我有一个问题:

我有一个
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;
map水果{
{“苹果”,5},{“葡萄柚”,7},{“樱桃”,10},{“葡萄”,16}
};
用于(const auto&p:水果)

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


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

您真的要比较键值和键值,还是只对键值感兴趣?如果是后者,则std::map有一个下限成员()@PhilippLenk:Yes。我明白了。我对常数的猜测正确吗?谢谢,这是常量,因为通过迭代器等修改键的值可能会破坏数据结构(因为节点必须重新排序)。安全地修改键可以通过C++17的extract()完成,它将为您提供一个从map@PhilippLenk:谢谢,好的。我真的试过了。因为在我的书中,有人说总是使用关联容器(算法)的成员,而不是使用泛型容器。但要加上第一部分关于康斯特内斯的问题。谢谢。好的,现在谢谢你。