Q:

how to copy an attribute of an object to a vector?

I have a vector<Person> and want to extract the attribute name of each object, to a vector<string>. The for-each loop does it job correctly, but is there a nicer way to use something like std::copy() and tell him to use a specific method (in this case the name() getter) to copy the values into my vector<string>?
class Person {
  int a;
  string n;
public:
  Person(int age, string name) : a(age), n(name) {}
  int age() const { return a; }
  string name() const { return n; }
};

vector<Person> ppl = { Person(12, "Tim"), Person(21, "Tom") };
vector<string> names;

// question
// copy(ppl.begin(), ppl.end(), ????.name());

for (Person& p : ppl)
  names.push_back(p.name());

copy(names.begin(), names.end(), ostream_iterator<string>(cout, ", "));

A:

How about std::transform with std::back_inserter:
std::transform(std::begin(ppl), std::end(ppl),
               std::back_inserter(names),
               [](const Person& p) -> std::string { return p.name(); });

In the end though, it's still basically the same as what you already have.

A:

A range-based for loop is usually the most straightforward way to do an arbitrary operation to each element of a container. There's also the transform algorithm:
transform(
    ppl.begin(), 
    ppl.end(), 
    back_inserter(names),
    [](Person const & p){return p.name();}
);

