MistyD
MistyD

Reputation: 17223

Why cant we use std::find with std::map

I am aware that std::map has its own find method. But I wanted to know why we cant use std::find. I tried this

int main()
{
    std::map<std::string,std::string> mp;
    mp["hello"] = "bye";
    if(std::find(mp.begin(),mp.end(),"hello")!=mp.end()))
    {
        std::cout << "found" ;
    }

}

and I get the exception

no matching function for call to 'find(std::map<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> >::iterator, std::map<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> >::iterator, const char [6])'
     if(std::find(mp.begin(),mp.end(),"hello")!=mp.end()))

Upvotes: 0

Views: 88

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

We can, but we have to pass the appropriate argument. The "value type" of a map is a pair consisting of the key (in const form) and the value. As such, you'd have to pass the entire pair of key and value in order to use std::find:

std::find(mp.begin(),mp.end(),std::make_pair("hello","hello"))

(or something like that)

Of course, in the specialised case of an associative container, that is silly: we usually only want to search on key. Hence the special std::map::find exists.

Also, a specialised searching tool that "knows about" a map's internal tree-like structure is far more efficient (think binary search!) than a version that just takes iterators to "some data that can be iterated", and thus must traverse the data linearly, in value order. That's why you want to use std::set::find, even though a set element's key is its value.

Upvotes: 3

Related Questions