Daniel
Daniel

Reputation: 365

How to copy specific items from a 2d vector using copy_if

As an example, I have a 2d vector and a 1d vector and I want to copy the first item from each row using std::copy_if from the algorithm library:

std::vector<std::vector<std::string>> names{ { "Allan", "Daniel", "Maria" }, {"John", "Louis", "Will"}, {"Bill", "Joe", "Nick"}};

So we'll have to copy "Allan", "John" and "Bill" into the destination vector which is dst

std::vector<std::string> dst;

Upvotes: 1

Views: 228

Answers (2)

cigien
cigien

Reputation: 60218

This is not the appropriate algorithm for your task. std::copy_if copies elements of a range if that element satisfies some predicate.

This might seem like you need to use std::copy, but that would be an issue because copy simply means, copy each element unconditionally.

In your case, the appropriate algorithm would be std::transform, since you want to transform each element of the range into a different type.

std::vector<std::string> dst;
std::transform(names.begin(), names.end(),
               std::back_inserter(dst), /* function */);

where function would be a lambda that returns just the first string from a vector<string>.

Upvotes: 0

Thomas Caissard
Thomas Caissard

Reputation: 866

You should use std::transform instead of std::copy_if:

std::transform(names.begin(), names.end(), std::back_inserter(dst),
    [](const std::vector<std::string>& v) { return v[0]; });

Upvotes: 6

Related Questions