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

Ita*_*iwa 1 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 << 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;
Run Code Online (Sandbox Code Playgroud)

所以我的问题是如何将第三个参数std::lower_bound显式传递给?

  • 因为得到帮助后,从typeid我已经注意到,对的firstconst这是因为键constants

  • 如果我传递给定键的值与容器中的键不匹配,也会发生什么。例如:带有key的元素"Cherry"具有一个值,10所以lower_bound如果我将value类似key 的值传递给它无效,为什么可以正常工作pair{"Cherry", 345}

  • 这对货币的价值传递给lower_bound任意吗?

Mar*_*som 6

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

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