使用find()函数时出错了。这是代码:
#include <iostream>
#include <map>
#define N 100000
using namespace std;
int main (int argc, char * const argv[]) {
map<int,int> m;
for (int i=0; i<N; i++) m[i]=i;
find(m.begin(), m.end(), 5);
return 0;
}
我收到了一个编译错误:
error: no match for 'operator==' in '__first. __gnu_debug::_Safe_iterator<_Iterator, _Sequence>::operator* [with _Iterator = std::_Rb_tree_iterator<std::pair<const int, int> >, _Sequence = __gnu_debug_def::map<int, int, std::less<int>, std::allocator<std::pair<const int, int> > >]() == __val'
包括'算法'没有任何变化。在VS2008中编译显示类似的错误。
我知道m.find(),但我真的需要使用find()。
非常感谢您的协助!
P.S。 Actualy,任务是比较m.find(5)和find(m.begin(),m.end(),5)的速度,所以我需要让它们都正常工作。
答案 0 :(得分:8)
begin()
和end()
都提供对这些集合元素的访问。这些元素的类型称为容器的value_type
。对于std::map<Key, Value>
,其value_type
为std::pair<Key, Value>
。因此,您的find
函数正在尝试查找等于5的pair<int, int>
。由于没有定义operator==
来比较pair<int, int>
和int
,因此错误。
执行此操作的正确方法(只要您想避开成员find()
)就是使用std::find_if
:
template <class First>
struct first_equal
{
const First value;
first_equal(const First& value)
: value(value)
{
}
template <class Second>
bool operator() (const std::pair<First, Second>& pair) const
{
return pair.first == value;
}
};
...
find_if(m.begin(), m.end(), first_equal<int>(5));
您还可以为operator==
和pair
重置int
以执行您想要的操作,但这是一种非常黑客的方式(因为它会影响您的所有代码,并且因为这样的比较一般没有意义。)
答案 1 :(得分:3)
find()需要一个可以与* iterator进行比较的参数。对于您的地图,这将是对&lt; int,int&gt;。你需要创建一个虚拟对,加上一个比较函数来比较这些对。
答案 2 :(得分:2)
只需使用m.find(5)