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

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


当前回答

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

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

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

其他回答

我知道这个问题已经有了一些很好的答案,但我认为我的解决方案值得分享。

它适用于std::map和std::vector<std::pair<T, U>>,从c++ 11可用。

template <typename ForwardIterator, typename Key>
bool contains_key(ForwardIterator first, ForwardIterator last, Key const key) {
    using ValueType = typename std::iterator_traits<ForwardIterator>::value_type;

    auto search_result = std::find_if(
        first, last,
        [&key](ValueType const& item) {
            return item.first == key;
        }
    );

    if (search_result == last) {
        return false;
    } else {
        return true;
    }
}
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<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;
}
map <int , char>::iterator itr;
    for(itr = MyMap.begin() ; itr!= MyMap.end() ; itr++)
    {
        if (itr->second == 'c')
        {
            cout<<itr->first<<endl;
        }
    }

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

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