C ++ class with an array of structures, not knowing how big the array I need

I have a class with fields like firstname, age, school, etc. I need to be able to store other information, such as where they traveled and what year it was. I cannot declare another class specifically for storing travelDestination and in which year, so I think the structure could be better. This is just an example:

struct travel {
    string travelDest;
    string year;
};

The problem is that people probably traveled for different amounts. I thought I had an array of travel structures for storing data. But how to create a fixed-size array to store them without knowing how big I need it?

Maybe I'm going to do it completely wrong, so any suggestions for a better way would be appreciated.


I understand that there is essentially no difference between a class and a structure, but for the purpose of the assignment criteria I am not allowed to have a “class”, so yes.

+3
source share
5 answers

You can try associating std :: vector with each person with every record in a vector containing a struct:

typedef struct travel {
    string travelDest;
    string year;
} travelRecord;

std::vector<travelRecord> travelInfo;

Then you can add elements to the vector as you like:

travelRecord newRecord1 = {"Jamaica", "2010"};
travelInfo.push_back(newRecord1);

travelRecord newRecord2 = {"New York", "2011"};
travelInfo.push_back(newRecord2);

More information about vector operations can be found here .

+9
source

Try learning about the standard C ++ Template Library (STL). For example, you can use list .

+1
source

, STL (, , , get/set accessors)

std::vector

::

...

, , . . - , , , .

STL: http://www.parashift.com/c++-faq-lite/class-libraries.html

+1

, stl, . ( ) , , :


#include <list>
#include <string>
using namespace std;

struct travel {
    string travelDest;
    string year;
};

int main() {
    list<travel> travels;
    travel t = {"Oslo", "2010"};
    travels.push_back(t);
}

, , , , . ++ , , , .

+1

100 , :

travel* pTravelArray = new travel[100];

int numberOfElements = 100;
travel* pTravelArray = new travel[numberOfElements];

, :

delete [] pTravelArray;

, STL ( - ), .

0
source

Source: https://habr.com/ru/post/1737627/


All Articles