Its my code
Its my code

Reputation: 11

C++ copy vector of objects to another

I want to copy to vectors with the same size and same type one to another but after printing the value it seems like it doesn't work correctly or it doesn't want to copy all pointers to data in each object. Thanks for help

Here is code:

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;

Output:

3

0

Here is the Vehicle code

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;
    }
};

Upvotes: 0

Views: 1711

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123431

You create two vectors with size 2. Then you push all elements from one vector to the other. You now have one unmodified vector and the other vector with 4 elements. Pushing two elements at the end wont have any effect on the first element (the one you print).

To copy vectors use simple assignment:

vehiclesCopy = vehicles;

Or if you want to use a loop (why would you?), assuming they both have correct size (they do in your example):

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

PS: this answer isnt the whole truth. If vehiclesCopy is really just a copy of vehicles you should not first construct an empty vector and then copy it, but instead use the right constructor. See here for details (overload (6) is your friend here).

Upvotes: 5

Related Questions