简体   繁体   English

如何将地图的内容从一个类别复制到另一个类别的新矢量

[英]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). 在我的C ++代码中,我有一个具有成对映射的类作为私有成员的类,我需要将这些对复制到新的向量中,该向量将保存在另一个类(也为私有)中。 If these containers were both in main(), I could do it pretty easily using copy(), but copy() won't work on my class. 如果这些容器都在main()中,则可以使用copy()轻松实现,但是copy()在我的类中不起作用。 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. 如果您有权访问类定义,则可以创建一个特殊的friend函数,该函数可用于访问每个类的私有成员并将私有成员从一个类复制到另一个类。

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 ... 当然,如果您可以访问类的定义,那么可以做很多事情,包括为其中一个类添加一个简单的方法,将一个类声明为另一个类的friend等。如果其他人创建了代码,并将这些数据成员声明为私有,那么他们要么错过了一个用例,要么您不应该使用该数据...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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