c++ map怎样根据索引的内容查找到key

来源:百度知道 编辑:UC知道 时间:2024/05/30 11:45:26

map<string,int>::iterator iter=ivec.find(k);
if(iter!=ivec.end())则找到
iter->first为key
iter->second为mapped

c++的std::map有两种方式可以实现依据索引的内容查找对应的键值

  1. 使用std::map的find接口。

    例子如下:

    std::map<std::string,int> mapTest;

    std::map<std::string,int>::iterator it = mapTest.find("index");

    if(it!=mapTest.end()) return it->second;

  2. 使用std::map的下标运算符重载

    例子如下:

    std::map<std::string,int> mapTest;

    return mapTest["index"];

注意,对于第二种方式存在安全隐患。如果对应的索引并不存在对应的键值的话,会有异常抛出。如果不捕获并处理的话可能导致程序崩溃。如果不确认索引是否存在键值,最好使用第一种方式,并添加查找失败的处理。

只能遍历了吧