Eitan
Eitan

Reputation: 47

Returned iterator from method like std::find_if does not match regular iterator

I have this std::find_if() like method that returns found iterator (that matches "condition" functor).

template<class T, class Function>
typename std::set<T>::iterator setFindIf(set<T> set, Function condition) {
    typename std::set<T>::iterator iterator = set.begin();
    for (; iterator != set.end(); iterator++) {
        cout<<"U";
        if (condition(*iterator)) {
            break;
        }
    }
    return iterator;
}

And this line that calls it:

std::set<Order>::iterator it = setFindIf(orders, orderCustomerHasOpenOrder(id, ordNum));

I'm testing on an empty set, so this line (that comes right after the above line) should print '1':

cout<<(it==orders.end());

Why doesn't this work? when I add this line at the end of the setFindIf() method, it prints '1' as expected.

Upvotes: 0

Views: 376

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

You're taking your set in by value. So it's a copy of the container that you passed in. Comparing those iterators is undefined behavior, because they belong to different containers. Pass the set in by reference instead.

Upvotes: 8

Related Questions