【问题标题】:Finding an element in a vector of structures在结构向量中查找元素
【发布时间】:2013-05-28 17:59:19
【问题描述】:

我按照这个https://stackoverflow.com/a/590005/1729501 回答并写了下面的代码。

#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector> 
using namespace std;

struct alpha {
    int x;
    int y;
};

struct find_element
{
    int y;
    find_element(int y) : y(y) {}
    bool operator ==( const alpha& l) const
    {
        return y == l.y;
    }
};

int main() {

    std::vector<alpha> vAlpha;
    vAlpha[0].x = 10;
    vAlpha[0].y = 100; 

    for(std::vector<alpha>::iterator it = vAlpha.begin(); it != vAlpha.end(); ++it) {
        int k = 100;
        // trying to find k in the complete vector
        if (vAlpha.end() == std::find_if( vAlpha.begin(), vAlpha.end(), find_element(k))) {
            cout << " not found! ";
        } else {
            cout << " found ";
        }
    }

    return 0;
}

这会导致编译错误

In file included from /usr/include/c++/4.7/algorithm:63:0,
                 from prog.cpp:2: /usr/include/c++/4.7/bits/stl_algo.h: In instantiation of
‘_RandomAccessIterator std::__find_if(_RandomAccessIterator,
_RandomAccessIterator, _Predicate, std::random_access_iterator_tag) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<alpha*,
std::vector<alpha> >; _Predicate = find_element]’:
/usr/include/c++/4.7/bits/stl_algo.h:4490:41:   required from ‘_IIter
std::find_if(_IIter, _IIter, _Predicate) [with _IIter =
__gnu_cxx::__normal_iterator<alpha*, std::vector<alpha> >; _Predicate = find_element]’ prog.cpp:30:88:   required from here /usr/include/c++/4.7/bits/stl_algo.h:210:4: error: no match for call
to ‘(find_element) (alpha&)’

如果我将find_element 结构移动到main() 中,我会得到以下错误,

prog.cpp: In function ‘int main()’: prog.cpp:31:88: error: no matching
function for call to ‘find_if(std::vector<alpha>::iterator,
std::vector<alpha>::iterator, main()::find_element)’ prog.cpp:31:88:
note: candidate is: In file included from
/usr/include/c++/4.7/algorithm:63:0,
                 from prog.cpp:2:

谁能告诉我正确的语法?

【问题讨论】:

    标签: c++ vector struct iterator


    【解决方案1】:

    正如其他人已经说过的,您需要实现operator() 而不是operator==。

    struct find_element
    {
        int y;
        find_element(int y) : y(y) {}
        bool operator()(const alpha& l) const
        {
            return y == l.y;
        }
    };
    

    那么你的用法是正确的:

    std::find_if(vAlpha.begin(), vAlpha.end(),
        find_element(k))
    

    如果您使用的是 C++11,您也可以为此使用 lambda:

    std::find_if(vAlpha.begin(), vAlpha.end(),
        [=](const alpha& l){ return k == l.y; })
    

    然后您可以完全省略您的 find_element 结构 - 单行 lambda 可以完成所有操作。非常简洁!

    【讨论】:

      【解决方案2】:

      您应该为算法提供函数调用运算符(),而不是相等运算符==。

      struct find_element
      {
          int y;
          find_element(int y) : y(y) {}
          bool operator () ( const alpha& l) const
          {
              return y == l.y;
          }
      };
      

      在 C++ 中称为函子。有关更多详细信息,请参阅this answer。

      【讨论】:

        【解决方案3】:

        std::find_if 需要一个 UnaryPredicate,尝试重载operator():

        struct find_element
        {
            int y;
        
            find_element(int y) : y(y)
            {
            }
        
            bool operator()(const alpha& l)
            {
               return y == l.y;
            }
        };
        

        【讨论】:

          【解决方案4】:

          你的函子应该重载 operator() 而不是 operator==

          struct find_element
          {
              int y;
              find_element(const int& y) : y(y) {}
              bool operator ()( const alpha& l) const
              //           ^^^^
              {
                  return y == l.y;
              }
          };
          

          如果你想重载==,那么对alpha 结构执行它并使用std::find,默认情况下将使用operator==


          其他问题。
          这是错误的

          std::vector<alpha> vAlpha;
          vAlpha[0].x = 10;
          vAlpha[0].y = 100;
          

          0 处还没有元素。您正在分配给一个不存在的成员。这是未定义的行为。应该是这样的

          std::vector<alpha> vAlpha(1);
          //                       ^^^  now it has 1 element
          vAlpha[0].x = 10;
          vAlpha[0].y = 100;
          

          或

          std::vector<alpha> vAlpha;
          alpha a;
          a.x = 10;
          a.y = 100; 
          vAlpha.push_back(a);
          

          【讨论】:

          • 你好,如何判断是使用find_if还是find?
          猜你喜欢
          • 1970-01-01
          • 2012-07-05
          • 1970-01-01
          • 1970-01-01
          • 2013-01-21
          • 1970-01-01
          • 1970-01-01
          • 2016-06-11
          相关资源
          最近更新 更多