我以这种方式使用 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;
}
我想获取其键以特定字符串(例如“Ab”)开头的所有值。我可以使用 map::lower_bound 轻松获得开始迭代器。但是我怎样才能得到上限呢?我是否必须从下限开始迭代整个集合并检查每个键是否仍以“Ab”开头?
最佳答案
我在这个页面找到了类似的答案:( map complex find operation )
代码练习:
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
}
看起来好像在这个例子中你从 upper_bound 向后迭代直到开始寻找特定的子串
这个例子略有不同,但应该是一个很好的构建 block
关于C++ std::map<std::string, int> 获取键以特定字符串开头的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16263060/