简体   繁体   中英

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.

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.

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

如果找不到项,则find_if返回等于_matrix.end()的迭代器。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM