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?
You want to use std::transform not std::copy and std::bind to bind to a pointer to a member variable:
#include
#include
#include
#include
#include
struct foo {
int a;
};
int main() {
const std::vector f = {{0},{1},{2}};
std::vector out;
out.reserve(f.size());
std::transform(f.begin(), f.end(), std::back_inserter(out),
std::bind(&foo::a, std::placeholders::_1));
// Print to prove it worked:
std::copy(out.begin(), out.end(), std::ostream_iterator(std::cout, "\n"));
}
My example is C++11, but if you skip the handy vector initalization and use boost::bind instead this works just as well without C++11.