Tom
Tom

Reputation: 9643

c++ - find_if condition?

How do you check if find_if has found a match or not? when i try the code below:

SparseMatrix& SparseMatrix::operator+=(const SparseMatrix &other)
{
    vector<Node>::iterator itThis;
    for (vector<Node>::const_iterator itOther = other._matrix.begin(); itOther != other._matrix.end(); ++itOther)
    {
        itThis = find_if(_matrix.begin(), _matrix.end(), position_finder(*itOther));

        if(*itThis)
        {
            itThis->value += itOther->value;
        } else
        {
            _matrix.push_back(*itOther);
        }
    }

    return *this;
}

I get at if(*itThis):

could not convert ‘itThis.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = Node*, _Container = std::vector<Node>, __gnu_cxx::__normal_iterator<_Iterator, _Container>::reference = Node&]()’ from ‘Node’ to ‘bool’

I understand that itThis is a constant so i cant change it's value but i want to know whether there was a match at all.

Upvotes: 2

Views: 2544

Answers (3)

odyss-jii
odyss-jii

Reputation: 2699

If an item is not found find_if returns an iterator equal to _matrix.end().

if (itThis == _matrix.end()) { ... }

Upvotes: 2

billz
billz

Reputation: 45410

find_if returns iterator to either element in container or to end(), see reference

You could compare itThis with _matrix.end()

if( itThis != _matrix.end())
{
}
else
{
}

Upvotes: 4

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272487

From http://en.cppreference.com/w/cpp/algorithm/find_if:

find_if( InputIt first, InputIt last, UnaryPredicate p )

...

Return value

Iterator to the first element satisfying the condition or last if no such element is found.

Upvotes: 4

Related Questions