我想复制到具有相同大小和相同类型的向量,但是在打印该值后,它似乎无法正常工作,或者它不想将所有指针复制到每个对象中的数据。感谢帮助
这是代码:
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;
Run Code Online (Sandbox Code Playgroud)
输出:
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;
}
};
Run Code Online (Sandbox Code Playgroud)
您创建了两个大小为2的向量。然后将所有元素从一个向量推到另一个向量。现在,您有一个未修改的向量,而另一个向量有4个元素。最后推两个元素不会对第一个元素(您打印的元素)产生任何影响。
要复制向量,请使用简单分配:
vehiclesCopy = vehicles;
Run Code Online (Sandbox Code Playgroud)
或者,如果您想使用循环(为什么?),请假设它们的大小都正确(在您的示例中是正确的):
for(int i=0;i<vehicles.size();i++) {
vehiclesCopy[i] = vehicles[i];
}
Run Code Online (Sandbox Code Playgroud)
PS:这个答案不是全部。如果vehiclesCopy
真的只是您的一个副本,则vehicles
不应首先构造一个空向量,然后再将其复制,而应使用正确的构造函数。有关详细信息,请参见此处(过载(6)是您的朋友)。