简体   繁体   中英

std::find on an (unordered_)map

For an unordered_map I have I want to do a reverse lookup (meaning to find the key given a value). One would expect this to be simple using std::find. I tried the following, which doesn't work:

#include <unordered_map>
#include <algorithm>

int main()
{
    std::unordered_map<int, int>    map;

    auto iter = std::find(map.begin(), map.end(), [](const std::pair<int, int> &pair) -> bool {
        return pair.second == 4;
    }); 
}

The compiler complains about an invalid binary expression, apparently it tries to compare the value to the predicate itself:

/usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0/../../../../include/c++/5.4.0/bits/predefined_ops.h:194:17: error: invalid operands to binary expression ('std::pair' and 'const (lambda at unordered_map.cpp:8:51)') { return *__it == _M_value; }

What am I missing here? As far as I know, this should be a valid predicate to search the map.

The std::find function is used to look for a value in the container. If you have a predicate you want to use then use std::find_if .

See eg this std::find and std::find_if reference .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM