Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use std::copy if an explicit type conversion is necessary between source and destination type

Tags:

c++

Consider

struct foo{};

struct bar{
    bar(const foo& f){}
};

And imagine that I have a

std::vector<foo> vec;

and I want to convert this to a std::vector<bar> out. I can use

std::copy(vec.begin(), vec.end(), std::back_inserter(out));

to do that since bar is not explicit. However, I need bar to be explicit! But then the back_inserter no longer works. What changes do I need to make to the std::copy parameters to somehow include the explicit bar(<iteratee>)?

like image 408
P45 Imminent Avatar asked Dec 30 '22 11:12

P45 Imminent


1 Answers

std::transform(
    vec.begin(),
    vec.end(),
    std::back_inserter(out),
    [](const foo& f){
        return bar(f);
    }
);

will do it.

like image 188
Bathsheba Avatar answered Jan 02 '23 00:01

Bathsheba