为什么我们不能使用std :: find和std :: map

时间:2018-02-15 00:25:39

标签: c++ stl

我知道std::map有自己的find方法。但我想知道为什么我们不能使用std::find。我试过这个

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

}

我得到了例外

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()))

1 个答案:

答案 0 :(得分:3)

我们可以,但我们必须传递适当的论点。地图的“值类型”是由密钥(以const形式)和值组成的对。因此,您必须传递整对键和值才能使用std::find

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

(或类似的东西)

当然,在关联容器的特殊情况下,这很愚蠢:我们通常只想搜索密钥。因此特殊std::map::find存在。

另外,一个专门的搜索工具“知道”一个地图的内部树状结构,效率要高得多(想想二元搜索!),而不仅仅是将迭代器带到“一些可以迭代的数据”的版本,因此必须以值的顺序线性遍历数据。这就是为什么你想使用std::set::find,即使set元素的键 是它的值。

相关问题