【问题标题】:c++ find_if can't find the predicatec++ find_if 找不到谓词
【发布时间】:2013-01-17 04:29:49
【问题描述】:

我收到了错误:

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

当我将 ik 转换为 int 时,我得到:

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;

【问题讨论】:

  • 如果找到元素,如何使用rowMulti?我只看到几个循环,但没有做任何其他事情?

标签: c++ algorithm vector


【解决方案1】:

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

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

你可以从错误中看到这一点

没有匹配函数调用‘findByPosition::findByPosition(int, int)’

它正在尝试寻找构造函数

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

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;
};

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

【讨论】:

    【解决方案2】:

    如果您使用C++11Lambda 是简单搜索的更好选择

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多