我正在以这种方式使用std :: map:
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
map<string, int> my_map;
my_map.insert(pair<string, int>("Ab", 1));
my_map.insert(pair<string, int>("Abb", 2));
my_map.insert(pair<string, int>("Abc", 3));
my_map.insert(pair<string, int>("Abd", 4));
my_map.insert(pair<string, int>("Ac", 5));
my_map.insert(pair<string, int>("Ad", 5));
cout<<my_map.lower_bound("Ab")->second<<endl;
cout<<my_map.upper_bound("Ab")->second<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我想获得其键以特定字符串开头的所有值(例如"Ab").我可以使用map :: lower_bound轻松获取begin迭代器.但是我怎样才能获得上限?我是否必须从下限开始迭代整个集合并检查每个键是否仍然以"Ab"开头?
我找到了类似的答案,请查看此页面:(地图复杂查找操作)
代码练习:
template<typename Map> typename Map::const_iterator
find_prefix(Map const& map, typename Map::key_type const& key)
{
typename Map::const_iterator it = map.upper_bound(key);
while (it != map.begin())
{
--it;
if(key.substr(0, it->first.size()) == it->first)
return it;
}
return map.end(); // map contains no prefix
}
Run Code Online (Sandbox Code Playgroud)
看起来好像在这个例子中你从 upper_bound 向后迭代直到开始寻找特定的子字符串
这个示例略有不同,但应该作为一个很好的构建块