Hm!
As I understood the task:
> vector<Person> persons;
> vector<Person2> persons2;
>
> // add 10 items into persons ....
> // add 10 items into persons2 ....
>
> Now, which std-function I can use to copy *only* the age-values from
> persons vector into persons2?
… it involves
• Two vectors of equal size, one hold Person items and the other holding
Person2 items. I.e. the latter is not empty.
• The `age` values in the latter should be /changed/.
It looks to me as if you're assuming instead that the `vp2` vector is
initially empty. Also, an assumption that at the end it should hold only
age values, with other items default-initialized. But this means that
the `height` items will have indeterminate values.
For example, when I added the following little driver code,
#include <iostream>
auto main()
-> int
{
vector<Person> vp = { {1, "One"}, {2, "Two"}, {3, "Three" } };
vector<Person2> vp2;
f( vp, vp2 );
for( auto const& p : vp2 )
{
cout << p.age << " " << p.height << " `" <<
p.name << "`"
<< endl;
}
}
which hopefully conforms to the assumptions in your code, it produced
1 4208845 ``
2 4208845 ``
3 4208845 ``
Changing the default initialization to one that carries over the data is
trivial, like this,
#include <assert.h>
void f_fixed( vector<Person> &vp, vector<Person2> &vp2 )
{
assert( vp2.size() == 0 );
vp2.reserve( vp.size() );
transform( vp.begin(), vp.end(), back_inserter( vp2 ),
[]( Person &p ) { Person2 p2{ p.age, 0,
p.name }; return
p2; } );
}
which gives the output
1 0 `One`
2 0 `Two`
3 0 `Three`
Then it's very clear that this is really a copying of transformed
values. I think that's very likely what the OP was really after. I.e.,
that the request to modify values was an X/Y-question.
• • •
As a matter of style I would add `const` for the vector of original
items, and instead of using an out-argument for the result I would
simply return it, like this:
auto f2( vector<Person> const& vp )
-> vector<Person2>
{
vector<Person2> result;
result.reserve( vp.size() );
transform( vp.begin(), vp.end(), back_inserter( result ),
[]( Person const& p ) { return Person2{ p.age, 0,
p.name };
} );
return result;
}
E.g. this allows the driver program to use `const`, and there's no need
for the `assert` any more – one degree of freedom for bugs is removed.
Cheers!,
- Alf