C ++将对象的向量复制到另一个

时间:2019-10-23 09:19:04

标签: c++ object vector

我想复制到具有相同大小和相同类型的向量,但是在打印该值后,它似乎无法正常工作,或者它不想将所有指针复制到每个对象中的数据。感谢您的帮助

这是代码:

std::vector<Vehicle> vehicles(2);
std::vector<Vehicle> vehiclesCopy(2);

vehicles[0].setX_pos(3);

for(int i=0;i<vehicles.size();i++)
    vehiclesCopy.push_back(vehicles[i]);

cout<<vehicles[0].getX_pos()<<endl;
cout<<vehiclesCopy[0].getX_pos()<<endl;

输出:

3

0

这是车辆代码

class Vehicle
{
private:
    unsigned int x_pos,y_pos,velocity;
    char type;
public:
    void vehicle(char           inType,
                unsigned int    inX_pos,
                unsigned int    inY_pos,
                unsigned int    inVelocity)
                {
                    type=inType;
                    x_pos=inX_pos;
                    y_pos=inY_pos;
                    velocity=inVelocity;
        }
    unsigned int getMaxPassengers(){
        return maxPassengers;
    }
    unsigned int getX_pos(){
            return x_pos;
        }
    unsigned int getY_pos(){
            return y_pos;
        }
    unsigned int getVelocity(){
            return velocity;
        }
    char getType(){
            return type;
        }
    void setX_pos(unsigned int input){
            x_pos=input;
        }
    void setY_pos(unsigned int input){
            y_pos=input;
        }
    void setVelocity(unsigned int input){
            velocity=input;
        }
    void setType(char input){
        type=input;
    }
};

1 个答案:

答案 0 :(得分:5)

创建两个大小为2的向量。然后将所有元素从一个向量推到另一个向量。现在,您有一个未修改的向量,而另一个向量有4个元素。最后推两个元素不会对第一个元素(您打印的元素)产生任何影响。

要复制向量,请使用简单分配:

vehiclesCopy = vehicles;

或者如果您想使用循环(为什么?),假设它们都具有正确的大小(在您的示例中也是如此):

for(int i=0;i<vehicles.size();i++) {
    vehiclesCopy[i] = vehicles[i];
}

PS:这个答案不是全部。如果vehiclesCopy实际上只是vehicles的副本,则您不应该先构造一个空向量然后再复制它,而应使用正确的构造函数。有关详细信息,请参见here(过载(6)是您的朋友)。

相关问题