c ++ find_if找不到谓词

时间:2013-01-17 04:29:50

标签: c++ algorithm vector

我收到了错误:

no matching function for call to ‘findByPosition::findByPosition(std::vector<int>::size_type&, std::vector<int>::size_type&)’

当我施展i&amp; kint我得到:

no matching function for call to ‘findByPosition::findByPosition(int, int)’

我不知道我的谓词有什么问题。我根据需要重载了()运算符:

struct findByPosition
{
    const Node needle;
    findByPosition(const Node& sought) : needle(sought) {}
    bool operator()(int i,int j) const
    {
        return ((needle.i == i) && (needle.j == j));

    }
};

SparseMatrix& SparseMatrix::operator*=(const SparseMatrix &other)
{
    SparseMatrix SparseMatrixResult(_numRow, other._numCol);
    vector<Node>::iterator rowMulti, colMulti;

    if(_numCol != other._numRow)
    {
        // error multiplying
    }

    for(std::vector<int>::size_type i = 0; i != (unsigned int)_numRow; i++) {

            for(std::vector<int>::size_type j = 0; j != (unsigned int)_numCol; j++) {

                for(std::vector<int>::size_type k = 0; k != (unsigned int)_numCol; k++)
                {
                    rowMulti = find_if(_matrix.begin(), _matrix.end(), findByPosition(i,k));
                }
            }
        }

    *this = SparseMatrixResult;
    return *this;
}

_matrix的类型为:

vector<Node> _matrix;

2 个答案:

答案 0 :(得分:4)

当您致电findByPosition(i,k)时,您实际上是尝试调用构造函数,而不是operator()

您需要定义构造函数,然后您可以在该行使用生成对象find_if然后会在内部调用theobject(i,j) 来调用operator()

您可以从错误

中看到此信息
  

没有匹配函数来调用'findByPosition :: findByPosition(int,int)'

它正在尝试找到构造函数

要正确使用谓词,您需要实际翻转运算符和构造函数。构造函数应该采用i,j,因为它对于函数的所有调用都是通用的,并且运算符应该引用const Node&,因为这是矩阵的元素类型,并且是函数将的数据类型被称为。

struct findByPosition
{
    findByPosition(int _i, int _j) : i(_i), j(_j) {}
    bool operator()(const Node& needle) const
    {
        return ((needle.i == i) && (needle.j == j));

    }
private:
    int i,j;
};

这样,构造函数将构造一个保存ij的对象,然后将其传递给find_if函数。

答案 1 :(得分:3)

如果您使用Lambda

C++11是简单搜索的更好选择

rowMulti = find_if(_matrix.begin(), _matrix.end(),
                  [=](const Node& n){return n.i==i && n.j == k; });
相关问题