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

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


当前回答

template <typename T, typename Key>
bool key_exists(const T& container, const Key& key)
{
    return (container.find(key) != std::end(container));
}

当然,如果你想要更花哨一点,你总是可以模板化一个函数,同时取一个已找到的函数和一个未找到的函数,就像这样:

template <typename T, typename Key, typename FoundFunction, typename NotFoundFunction>
void find_and_execute(const T& container, const Key& key, FoundFunction found_function, NotFoundFunction not_found_function)
{
    auto& it = container.find(key);
    if (it != std::end(container))
    {
        found_function(key, it->second);
    }
    else
    {
        not_found_function(key);
    }
}

像这样使用它:

    std::map<int, int> some_map;
    find_and_execute(some_map, 1,
        [](int key, int value){ std::cout << "key " << key << " found, value: " << value << std::endl; },
        [](int key){ std::cout << "key " << key << " not found" << std::endl; });

缺点是要想出一个好名字,“find_and_execute”是尴尬的,我不能想出任何更好的在我的头顶…

其他回答

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

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

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

map <int , char>::iterator itr;
    for(itr = MyMap.begin() ; itr!= MyMap.end() ; itr++)
    {
        if (itr->second == 'c')
        {
            cout<<itr->first<<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。如果m.find("f")等于m.end(),则没有找到该键。否则,find返回指向所找到元素的迭代器。

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

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

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