【问题标题】:C++ copy vector of objects to anotherC ++将对象的向量复制到另一个
【发布时间】:2019-10-23 09:19:04
【问题描述】:

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

代码如下:

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.为 Vehicle 定义一个复制限制器(因为您只有简单的类型行intchar,默认复制限制器就足够了); 2. std::vector 车辆复制(车辆);
  • @SergeyAleksandrovich 不,这无关紧要。请参阅零规则
  • 抱歉,假设问题出在您未显示的代码中(在编辑之前),但无论如何关于代码问题的问题应该呈现一个 mcve。如果没有看到 Vehicle 的定义,可能会出现比您首先发布的 sn-p 中明显的更多错误
  • @molbdnilo 当你想创建向量时,没有带参数的构造函数会更容易,
  • 不确定,但可能 molbdnilo 引用了std::vector 的构造函数,请参阅我刚刚在答案中添加的 PS

标签: c++ object vector


【解决方案1】:

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

复制向量使用简单的赋值:

vehiclesCopy = vehicles;

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

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

PS:这个答案并不是全部真相。如果vehiclesCopy 真的只是vehicles 的副本,则不应先构造一个空向量然后再复制它,而应使用正确的构造函数。详情见here(overload (6) 是你的朋友)。

【讨论】:

  • 我试过你的解决方案,但还是不行,输出和以前一样
  • @Itsmycode “它不起作用”是什么意思?
  • @Itsmycode 如果您发布您的代码,例如here,我可以查看它。如果是新问题,可能会打开一个新问题
  • 表示输出还是一样的,我试过这个std::vector vehicleCopy(vehicle);还有车辆复制=车辆;但输出仍然是 3 0
  • @Itsmycode 在这里按预期工作:wandbox.org/permlink/ZEAWi0DNfoJ0nBvl 你的代码中一定有其他问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-06
  • 1970-01-01
  • 2021-01-23
  • 2016-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多