C++ std::map<std::string, int> 获取键以特定字符串开头的值

标签 c++ map

我以这种方式使用 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;
}

http://ideone.com/5YPQmj

我想获取其键以特定字符串(例如“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/

相关文章:

c++ - 将 `auto` 关键字与 STL 迭代器一起使用

c++ - 在任何地方绘制一个类似系统的光标,最顶层

c++ - 从不可 move 对象的函数返回拷贝

c++ - 简称 vector 索引

php - php中有 "map"函数吗?

c++ - 错误 : c++ [map] does not name a type

c# - 使用 linq 查询输出列表/其他数据结构

c++ - 对象和数据成员内存地址困惑

c++ - 调试时如何在 Visual C++ .NET (Visual Studio 2003) 中查看 std::map 的内容?

java - 将 map 用于图形