Search code examples
c++std

C++ vector: for loop to std::transform


I got a code in the following form

vector<int> vec{ 1,2,3 };
vector<int> vec2{ 4, 5, 6, 7, 8, 9 };

for (int i = 0; i < vec2.size(); i++) {
    if (vec2[i] % 2 == 0)
        vec.push_back(vec2[i]);
}

How can I use std::transform to get rid of the for loop? Thanks for help :)

I tried something like:

std::transform(vec2.begin(), vec2.end(), std::back_inserter(vec), ...);

but I'm not sure what to add in the last place (where the ... are).


Solution

  • What you want is a std::copy_if:

        std::vector<int> vec{ 1,2,3 };
        std::vector<int> vec2{ 4, 5, 6, 7, 8, 9 };
    
        std::copy_if(vec2.cbegin(),vec2.cend(),std::back_inserter(vec),[](const int num){
            return num % 2 == 0;
        });
        for(auto&& i : vec) {
            std::cout << i;
        }
    

    std::copy_if copies element from one range to another, using a predicate as the selection criteria.

    std::transform is a mapping from one range to another: T -> transform-> U