Tom
Tom

Reputation: 9643

c++ find_if can't find the predicate

I'm getting the error:

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

And when I cast i & k to int i get:

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

I don't know what's the problem with my predicate. I've overloaded the () operator as needed:

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 is of type:

vector<Node> _matrix;

Upvotes: 2

Views: 977

Answers (2)

billz
billz

Reputation: 45410

Lambda is a better option for simple search if you use C++11

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

Upvotes: 3

Karthik T
Karthik T

Reputation: 31952

When you call findByPosition(i,k) you are actually trying to call the constructor, not the operator()

You need to define a constructor that you can then use at that line to generate an object. find_if then will call theobject(i,j) internally to invoke the operator()

You can see this from the error

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

It is trying to find the constructor.

To correctly use the predicate, you need to actually flip your operator and your constructor. The constructor should take i,j as it is common to all calls of the functor, and the operator should take reference to the const Node& since that is the element type of the matrix and is the datatype that the functor will be called with.

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

With this, the constructor will construct an object with i,j saved, which will then be passed to your find_if function.

Upvotes: 5

Related Questions