0

我有这个问题:

我有一个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,为什么可以正常工作?lower_boundvaluepair{"Cherry", 345}

  • 该对的值是否传递给lower_bound任意值?

4

1 回答 1

7

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

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

于 2019-10-06T23:33:31.003 回答