我在使用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;
}我收到一个compiller错误:
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()。
非常感谢您的帮助!
附注:实际上,任务是比较m.find(5)和find(m.begin(),m.end(),5)的速度,所以我需要让它们都能正常工作。
发布于 2009-07-17 22:01:30
所有STL容器上的begin()和end()都提供了对这些集合元素的访问。这些元素的类型称为容器的value_type。对于std::map<Key, Value>,它的value_type是std::pair<Key, Value>。因此,您的find函数试图找到一个等于5的pair<int, int>。因为没有定义用于比较pair<int, int>和int的operator==,所以您会得到错误。
执行此操作的正确方法(只要您希望避免成员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));您也可以重载pair和int的operator==来做您想做的事情,但这是一种非常老套的方式(因为它会影响您的所有代码,而且这种比较通常没有意义)。
发布于 2009-07-17 21:52:31
find()需要一个可以与*iterator进行比较的参数。对于您的地图,这将是pair。您将需要创建一个虚拟对,外加一个比较函数来比较这些对。
发布于 2009-07-17 21:57:59
只需使用m.find(5)
https://stackoverflow.com/questions/1145849
复制相似问题