user1759558
user1759558

Reputation: 41

how to insert into vector under condition without use loop?

I would like to copy elements from one vector which meet certain criteria in to another vector, but without using a hand-written loop. For example,

std::vector<double> source; // somehow filled elsewhere
std::vector<double> result;

for( std::vector<double>::const_iterator it = source.begin(); it != source.end(); ++it )
{
   if ((*it) % 2)
   {
      result.push_back(*it);
   }
}

The above code uses a hand-written loop to populate result. How can this be done without a hand-written loop?

Upvotes: 2

Views: 684

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

You can use std::copy_if() and std::back_inserter() to do so. To get the initial sequence with suitable values you can use std::generate_n(). I could type things out but you'd be better off doing the homework.

Upvotes: 4

Related Questions