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

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更有趣。

其他回答

比较std::map::find和std::map::count的代码,我会说第一个可能会产生一些性能优势:

const_iterator find(const key_type& _Keyval) const
    {   // find an element in nonmutable sequence that matches _Keyval
    const_iterator _Where = lower_bound(_Keyval); // Here one looks only for lower bound
    return (_Where == end()
        || _DEBUG_LT_PRED(this->_Getcomp(),
            _Keyval, this->_Key(_Where._Mynode()))
                ? end() : _Where);
    }

size_type count(const key_type& _Keyval) const
    {   // count all elements that match _Keyval
    _Paircc _Ans = equal_range(_Keyval); // Here both lower and upper bounds are to be found, which is presumably slower.
    size_type _Num = 0;
    _Distance(_Ans.first, _Ans.second, _Num);
    return (_Num);
    }

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

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

我想你需要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更有趣。

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;
}

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

它适用于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;
    }
}