Howard1471
Howard1471

Reputation: 73

How do I use C++ vectors with a user defined structure?

I am trying to manage an array of structures using vectors but keep getting an error msg.

The vector is declared in the header file as:

vector< TLE_Values, allocator<TLE_Values> > SavedSatellites;

which VS2013 is quite happy with.

The structure is defined as:

struct TLE_Values
{
    string CatalogNum;
    string SatelliteName;
    string DateStr;
    string TimeStr;
    string Classification;
    double DecayValue;
    int ElsetNum;
    double InclinationValue;
    double RaanValue;
    double EccentricityValue;
    double ArgPerigeeValue;
    double PerigeeAngle;
    double AvgSpeed;
    double Period;              
    int OrbitNum;
};

and initialised with default values by a constructor.

In the main program code, having determined the number of elements I will require ( CountItemsInFile() ), I try to expand the vector list using:

SavedSatellites.push_back(CountItemsInFile());

This however returns the following compiler error message:

error C2664: 
'void std::vector<TLE_Values,std::allocator<TLE_Values>>::push_back(const TLE_Values &)' : cannot convert argument 1 from 'int' to 'TLE_Values &&'
1>          Reason: cannot convert from 'int' to 'TLE_Values'
1>          No constructor could take the source type, or constructor overload resolution was ambiguous.

Another thread suggested that a vector needed to be initialised with 0, which won't happen with a user defined type like this. What am I missing? where have I gone wrong? How do I create the initial vector with my structure? There's lots of documentation for using vectors of type (int) but not much if you're not using integers.

Upvotes: 0

Views: 453

Answers (2)

Miroslaw Opoka
Miroslaw Opoka

Reputation: 119

To expand a vector use

SavedSatellites.resize(CountItemsInFile());

If you just want reserve memory for it but keep the size of the vector untouched and ready for subsequent push_back without memory reallocation:

SavedSatellites.reserve(CountItemsInFile());

Upvotes: 3

cf-
cf-

Reputation: 8866

The docs are key here:

void push_back (const value_type& val);

push_back doesn't take an int, it takes a parameter of the same type your vector holds. You need to give it a TLE_Values object.

You also don't need to preemptively size the vector; you can just keep calling push_back until you're done.

Upvotes: 1

Related Questions