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

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和map::end:

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

其他回答

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

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

c++ 20给了我们std::map::contains来做这个。

#include <iostream>
#include <string>
#include <map>

int main()
{
    std::map<int, std::string> example = {{1, "One"}, {2, "Two"}, 
                                     {3, "Three"}, {42, "Don\'t Panic!!!"}};

    if(example.contains(42)) {
        std::cout << "Found\n";
    } else {
        std::cout << "Not found\n";
    }
}

比较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);
    }

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

你可以使用.find():

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

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