我在使用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;
}
Run Code Online (Sandbox Code Playgroud)
我收到了一个编译器错误:
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'
Run Code Online (Sandbox Code Playgroud)
包括'算法'没什么变化.在VS2008中编译显示类似的错误.
我知道m.find(),但我真的需要使用find().
感谢你的帮助.
PS Actualy,任务是比较m.find(5)和find(m.begin(),m.end(),5)的速度,所以我需要让它们都正常工作.
begin()并且end()在所有STL容器上提供对这些集合的元素的访问.这些元素的类型已知为value_type容器的类型.因为std::map<Key, Value>它value_type是std::pair<Key, Value>.因此,你的find函数试图找到一个pair<int, int>等于5.由于没有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));
Run Code Online (Sandbox Code Playgroud)
你也可以超载operator==的pair和int做你想做的,但它是一个非常hackish的方式(因为它会影响您所有的代码,因为这样的比较有一般没有意义).
| 归档时间: |
|
| 查看次数: |
422 次 |
| 最近记录: |