在成对向量中查找函数时出错

Error in Find function in vector of pairs

本文关键字:函数 出错 查找 向量      更新时间:2023-10-16

在这个函数中,我搜索向量缓存中的第一对。矢量为:

vector<pair<double,unsigned int> > cache;

我在查找功能中使用的自定义功能是:

struct comp
{
comp(double const& s) : _s(s) { }
bool operator () (pair<double, unsigned int> const& p)
{
return (p.first == _s);
}
double _s;
};

我将find函数称为:

it = find(cache.begin(),cache.end(),comp(value));

在编译方面,我遇到了很多错误。前几行是:

在/usr/include/c++/4.6/agorithm:63:0中包含的文件中,从my_class.hpp:5,来自main.cpp:5:/usr/include/c++/4.6/bits/stl_alg.h:在函数'RandomAccessIterator std::_find(_RandomAccessItator,_RandomAccess iterator,const_Tp&,std::random_access_iterator_tag)[其中_RandomAccessIterator=__gnu_cxx::__normal_iterator*,std:;vector>>,_Tp=MyCode::MyClass::comp]'中:/usr/include/c++/4.6/bits/stl_algo.h:4236:445:从'_IIter std::find(_IIter,_IIter、const_Tp&)实例化[其中_IIter=__gnu_cxx::__normal_iterator*,std::vector>>,_Tp=MyCode::MyClass::comp]'my_class.hpp:76:53:从这里实例化/usr/include/c++/4.6/bits/stl_algo.h:162:4:错误:首先在'_中没有匹配的'operator=='_gnu_cxx::__normal_iterator&lt_迭代器,_Container>::运算符*,其中_Iterator=std::对*,_Container=std::vector>,__gnu_cxx::__normal_Iterator&lt_迭代器,_Container>::reference=std::对&==__val’

如何解决此错误?

您传递的是谓词,而不是值,因此您需要find_if(),而不是find()

您的调用应该使用std::find_if,而不是std::find

it = find_if(cache.begin(),cache.end(),comp(value));
if ( it != cache.end() )
{

}