c++ - Is std::remove_if guaranteed to call predicate in order? -


will std::remove_if call predicate on each element in order (according iterator's order) or called out of order?

here toy example of do:

void processvector(std::vector<int> values) {     values.erase(std::remove_if(values.begin(), values.end(), [](int v)     {         if (v % 2 == 0)         {             std::cout << v << "\n";             return true;         }         return false;     })); } 

i need process , remove elements of vector meet criteria, , erase + remove_if seems perfect that. however, processing has side effects, , need make sure processing happens in order (in toy example, suppose want print values in order appear in original vector).

is safe assume predicate called on each item in order?

i assume c++17's execution policies disambiguate this, since c++17 isn't out yet doesn't me.

edit: also, idea? or there better way accomplish this?

the standard makes no guarantees on order of calling predicate.

what ought use stable_partition. partition sequence based on predicate. can walk partitioned sequence perform whatever "side effect" wanted do, since stable_partition ensures relative order of both sets of data. can erase elements vector.

stable_partition has used here because erase_if leaves contents of "erased" elements undefined.

in code:

void processvector(std::vector<int> values) {     auto = std::stable_partition(begin(values), end(values), [](int v) {return v % 2 != 0;});      std::for_each(it, end(values), [](int v) {std::cout << v << "\n";});      values.erase(it, end(values)); } 

Comments