Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Given a std::vector which holds objects of MyClass. How can I create another vector which holds just data of one member of MyClass using std::copy? I guess I would have to implement a custom back_inserter but I could not figure out how to do this so far.

struct MyClass {
   int a;
}

std::vector<MyClass> vec1;

// I could copy that to another vector of type MyClass using std::copy.
std::copy(vec1.begin(), vec1.end(); std::back_inserter(someOtherVec)

// However I want just the data of the member a, how can I do that using std::copy?
std::vector<int> vec2;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
451 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use std::transform for that.

std::transform(vec1.begin(), vec1.end(), std::back_inserter(vec2),
               [](const MyClass& cls) { return cls.a; });

(If you can't use C++11, you could make a function object yourself:

struct AGetter { int operator()(const MyClass& cls) const { return cls.a; } };

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

or use std::tr1::bind if you can use TR1:

std::transform(vec1.begin(), vec1.end(), std::back_inserter(vec2),
               std::tr1::bind(&MyClass::a, std::tr1::placeholders::_1));

BTW, as @Nawaz commented below, do a .reserve() to prevent unnecessary reallocation during the copy.

vec2.reserve(vec1.size());
std::transform(...);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...