如何使用 copy_if 从二维向量复制特定项目

Dan*_*iel 1 c++ vector c++11

例如,我有一个二维向量和一个一维向量,我想使用算法库中的std::copy_if从每一行复制第一项:

std::vector<std::vector<std::string>> names{ { "Allan", "Daniel", "Maria" }, {"John", "Louis", "Will"}, {"Bill", "Joe", "Nick"}};
Run Code Online (Sandbox Code Playgroud)

因此,我们必须将“Allan”、“John”和“Bill”复制到目标向量中,即 dst

std::vector<std::string> dst;
Run Code Online (Sandbox Code Playgroud)

Tho*_*ard 6

您应该使用std::transform代替std::copy_if

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