lundi 18 septembre 2017

Print comma separated list from std::vector with std::copy and lambda?

I'm trying to print a comma separated list of a single detail from a std::vector<MyClass>. So far the simplest and cleverest way I have seen to do this is to use

std::ostringstream ss;
std::copy(vec.begin(), vec.end() - 1, std::ostream_iterator<std::string>(ss, ", "))
ss << vec.back();

That worked fine when I was printing a vector of strings. However, now I am trying to print a single detail about MyClass. I know in Python I could do something like

(x.specific_detail for x in vec)

to get a generator expression for the thing that I am interested in. I'm wondering if I can do something similar here or if I am stuck doing

for (auto it = vec.begin(); it != vec.end(); ++it) {
    // Do stuff here
}

Aucun commentaire:

Enregistrer un commentaire