简体   繁体   中英

C++ How to copy this array type to a Vector

C++ How to copy this array type to a Vector

I got this array which is of class VehicleTwoD

I declare it this way at main function

VehicleTwod *vechicletwod[100];

//after some computation
//vechicletwod got until [5];

//now i need do sorting, but i prefer do it in vector. how do i copy the content of vehicletwod into an vector of the same type

I did something like

vector<VehicleTwoD> sortVector;
sortVector = shapetwod;

but i get some error for no match operator= in sortVector = vehicletwod;

Thanks for all help !

Unfortunately, your going to have loop through the array:

for (const auto& p : vechicletwod)
{
    sortVector.emplace_back(*p);
}

The better option would be to just use vector<VehicleTwoD> sortVector; from the start.

I'd just make a vector of type *VehicleTwod, ie vector<*VehicleTwod> sortVector. You could then iterate through your array and push_back each element.

Perhaps something like this:

typedef vector<*VehicleTwod> vecPtrVehicle2d;
typedef vecPtrVehicle2d::iterator vecPtrVehicle2dIter;

vecPtrVehicleWod sortVector;
int i, n = 100;

for (i=0; i<n; i++)
  sortVector.push_back(vechicletwod[i]);

You don't need the vector iterator just here, I tend to do it by habit.

Your types are inconsistent.

VehicleTwod *vechicletwod[100];

declares an array of VehicleTwod pointers , while your vector is declared to store actual VehicleTwod objects, not their memory addresses. Try initializing vechicletwod without the '*':

 VehicleTwod vechicletwod[100]; //array of actual objects

or changing the vector to contain pointers:

vector<VehicleTwoD*> sortVector;

Once the types work out, you can use the '=' operator exactly as you tried in the first place.

   sortVector = vehicletwod; //overloaded = operator in class vector

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM