我知道 std::map
有自己的查找方法。但我想知道为什么我们不能使用 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()))
最佳答案
我们可以,但我们必须传递适当的参数。映射的“值类型”是由键(const
形式)和值组成的一对。因此,您必须传递整对键和值才能使用 std::find
:
std::find(mp.begin(),mp.end(),std::make_pair("hello","hello"))
(或类似的东西)
当然,在关联容器的特殊情况下,这是愚蠢的:我们通常只想搜索键。因此存在特殊的 std::map::find
。
此外,“了解” map 内部树状结构的专用搜索工具比仅将迭代器获取“一些可以迭代的数据”的版本更有效(想想二进制搜索!),因此必须按值顺序线性遍历数据。这就是您要使用 std::set::find
的原因,即使 set 元素的键是它的值。
关于c++ - 为什么我们不能将 std::find 与 std::map 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48798383/