我试图检查一个给定的键是否在一个映射中,有点不能这样做:

typedef map<string,string>::iterator mi;
map<string, string> m;
m.insert(make_pair("f","++--"));
pair<mi,mi> p = m.equal_range("f");//I'm not sure if equal_range does what I want
cout << p.first;//I'm getting error here

那么我怎么打印p中的内容呢?


当前回答

我想你需要map::find。如果m.find("f")等于m.end(),则没有找到该键。否则,find返回指向所找到元素的迭代器。

这个错误是因为p.first是一个迭代器,它不适用于流插入。将最后一行更改为cout << (p.first)->first;。P是一对迭代器,P .first是一个迭代器,P .first->first是关键字串。

一个map对于一个给定的键只能有一个元素,所以equal_range不是很有用。它是为map定义的,因为它是为所有关联容器定义的,但它对multimap更有趣。

其他回答

m.find == m.end() // not found 

如果你想使用其他API,那么找到m.count(c)>0

 if (m.count("f")>0)
      cout << " is an element of m.\n";
    else 
      cout << " is not an element of m.\n";
map <int , char>::iterator itr;
    for(itr = MyMap.begin() ; itr!= MyMap.end() ; itr++)
    {
        if (itr->second == 'c')
        {
            cout<<itr->first<<endl;
        }
    }

在将查找结果与地图'm'的结果进行比较时要小心,因为所有答案都有 完成以上 Map::iterator I = m.find("f");

 if (i == m.end())
 {
 }
 else
 {
 }  

如果迭代器I等于m.end(),你不应该尝试执行任何操作,比如打印键或值,否则会导致分割错误。

要检查映射中是否存在特定的键,可以通过以下方式之一使用count成员函数:

m.count(key) > 0
m.count(key) == 1
m.count(key) != 0

map::find的文档说:“另一个成员函数map::count可用于检查特定键是否存在。”

map::count的文档说:“因为map容器中的所有元素都是唯一的,所以函数只能返回1(如果找到元素)或0(否则)。”

要通过已知存在的键从映射中检索值,请使用map::at::

value = m.at(key)

与map::operator[]不同,如果指定的键不存在,map::at将不会在映射中创建一个新的键。

使用map::find和map::end:

if (m.find("f") == m.end()) {
  // not found
} else {
  // found
}