I wanted to replace the loop with an algorithm in the following code
int numbers[] = { ... }; vector<int> output; for( int* it = numbers+from; it != numbers+to ; ++it ) { int square = func( *it ); if( predicate(square) ) { output.push_back(square); } }
The program is designed to convert values ββand copy them to the destination, if a condition occurs.
- I could not use
std::copy_if because this would not apply the conversion. - I could not use
std::transform because it lacks a predicate - It is not recommended to even write
transform_copy_if() because of the intermediate copy of the converted variable.
It seems like my only hope is to create a conditional_back_insert_iterator . Then I could have a pretty decent call like:
int numbers[] = { ... }; vector<int> output; std::transform(numbers+from, numbers+to, conditional_back_inserter(predicate, output), func);
Is this the best way to treat such cases? I couldn't even google for conditional inserts, so I'm worried that I'm wrong.
I could also suggest that I could implement an alternative solution such as
std::copy_if( transform_iterator<func>(numbers+from), transform_iterator<func>(numbers+to), back_inserter(output) );
(which reminds me of the * filter_iterators * example in boost) but it does not give readability.
source share