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

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中的内容呢?


当前回答

c++ 17用带初始化式的If语句简化了这一点。 这样你就可以鱼与熊掌兼得了。

if ( auto it{ m.find( "key" ) }; it != std::end( m ) ) 
{
    // Use `structured binding` to get the key
    // and value.
    const auto&[ key, value ] { *it };

    // Grab either the key or value stored in the pair.
    // The key is stored in the 'first' variable and
    // the 'value' is stored in the second.
    const auto& mkey{ it->first };
    const auto& mvalue{ it->second };

    // That or just grab the entire pair pointed
    // to by the iterator.
    const auto& pair{ *it };
} 
else 
{
   // Key was not found..
}

其他回答

如果你想比较一对地图,你可以使用这个方法:

typedef map<double, double> TestMap;
TestMap testMap;
pair<map<double,double>::iterator,bool> controlMapValues;

controlMapValues= testMap.insert(std::pair<double,double>(x,y));
if (controlMapValues.second == false )
{
    TestMap::iterator it;
    it = testMap.find(x);

    if (it->second == y)
    {
        cout<<"Given value is already exist in Map"<<endl;
    }
}

这是一个有用的技巧。

map<string, string> m;

检查键是否存在,返回出现的个数(map中0/1):

int num = m.count("f");  
if (num>0) {    
    //found   
} else {  
    // not found  
}

检查键是否存在,并返回迭代器:

map<string,string>::iterator mi = m.find("f");  
if(mi != m.end()) {  
    //found  
    //do something to mi.  
} else {  
    // not found  
}  

在你的问题中,错误操作符<<重载引起的错误,因为p.first是映射<字符串,字符串>,你不能打印出来。试试这个:

if(p.first != p.second) {
    cout << p.first->first << " " << p.first->second << endl;
}

你可以使用.find():

map<string,string>::iterator i = m.find("f");

if (i == m.end()) { /* Not found */ }
else { /* Found, i->first is f, i->second is ++-- */ }

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

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

要检查映射中是否存在特定的键,可以通过以下方式之一使用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将不会在映射中创建一个新的键。