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