简体   繁体   中英

How do I copy the contents of a map from one class into a new vector from another class

In my C++ code, I have a class that has a map of pairs as a private member, and I need to copy those pairs into a new vector that will be held in a different class (also private). If these containers were both in main(), I could do it pretty easily using copy(), but copy() won't work on my class. What's the most straightforward approach given my constraints?

If you have access to the class definitions, you could create a special friend function that can be used to access the private members of each class and copy the private members from one class to another.

For instance:

class B; //forward declaration

class A
{
    private:
        //... private data members

    public:
        //... methods, etc.

        friend void copy(const A&, B&);
};

class B
{
    private:
        //... private data members

    public:
        //... methods, etc.

        friend void copy(const A&, B&);
};

void copy(const A& rhs, B& lhs)
{
    //... copy the private elements out of class A into class B
}

Of course then again, if you had access to the class definitions, there's a number of things you could do including adding a simple method to one of the classes, declaring one class the friend of the other, etc. If someone else created the code and declared those data-members private, then either they missed a use-case or you shouldn't be touching that data ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM