对向量中的查找函数出错

时间:2014-03-02 11:42:00

标签: c++ vector compilation iteration std

在此函数中,我在向量缓存中搜索pair.first。矢量是:

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/algorithm:63:0中包含的文件中,                    来自my_class.hpp:5,                    来自main.cpp:5:       /usr/include/c++/4.6/bits/stl_algo.h:在函数' RandomAccessIterator std :: _find(_RandomAccessIterator,_RandomAccessIterator,const _Tp&amp;,std :: random_access_iterator_tag)[with _RandomAccessIterator = __gnu_cxx: :__ normal_iterator *,std :: vector&gt; &gt;,_ Tp = MyCode :: MyClass :: comp]':       /usr/include/c++/4.6/bits/stl_algo.h:4326:45:从'_IIter std :: find(_IIter,_IIter,const _Tp&amp;)实例化[与_IIter = __gnu_cxx :: __ normal_iterator *,std :: vector &GT; &gt;,_ 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; _Iterator,_Container&gt; :: operator * with _Iterator = std :: pair *,_ _Container = std :: vector&gt ;, __gnu_cxx :: __ normal_iterator&lt; _Iterator,_Container&gt; :: reference = std :: pair&amp; == __val'

如何解决此错误?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您的来电应使用std::find_if,而不是std::find

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


 }