samedi 31 octobre 2020

How do I display the contents of a std::vector of my own datatype and displaying the name on the console using std::copy?

Hi Stackoverflow community, I have a little bit of a problem. I would like to display the contents of the std::vector using std::copy similar to how I've achieved it through std::for_each (see in the main). Is it possible to achieve this? Many thanks in advance to anyone who provides me a solution.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
class User {
private:
    std::string m_sName;
public:
    User(std::string sName):m_sName(sName) {}
    std::string GetName()const {
        return m_sName;
    }
};
int main()
{
    std::vector<User> vectNames;
    vectNames.emplace_back("Jack");
    vectNames.emplace_back("George");
    vectNames.emplace_back("Jose");
//How can I get std::copy to do what the std::for_each is doing?
    std::copy(vectNames.begin(), vectNames.end(), std::ostream_iterator<User>(std::cout, "\n"));
//The following line is what I really would like std::copy to do. 
    std::for_each(vectNames.begin(), vectNames.end(), [](const User &user) {std::cout << user.GetName() << "\n"; });
    
}

Aucun commentaire:

Enregistrer un commentaire