How does it work to use a vector of type struct? (C ++)


I would like help with understanding how to declare a vector of type struct. In the example of the code below I create the struct configcarros and would like to create a vector of the type of this structure and later access num_car and tempodevolta inserting values inside the vector.

    struct configcarros{

        int num_car, tempodevolta;


    int main(){

        int C,V, tempo;
        struct configcarros cars_ORD;
        cin >> C >> V;
        vector<struct configcarros> cars(C);


Could anyone help me understand this? I'm not finding much searching for struct vectors.

asked by anonymous 28.10.2017 / 03:06

1 answer


I start by saying that, as @RicardoPontual indicated in the comments, C ++ does not need to include the word struct in the use of the structure. In addition, since% w / o% of something with dynamic size can cut the startup it has, and simplify the declaration by leaving only:

vector<configcarros> cars;

Insert structures in <vector>

To insert structures into the vector, you can create the structure itself, set its values, and add through the <vector> :

configcarros c1; //criar objeto da estrutura
c1.num_car = 1; //definir o valor para num_car
c1.tempodevolta = 30; //definir o valor para tempodevolta

cars.push_back(c1); //adicionar ao vetor

You can even use a more direct boot by doing:

configcarros c2{2, 35}; //inicializar logo com os 2 valores

Or do everything inline :


Read structures stored in push_back

The reading is done as if it were a normal array using <vector> and [ , placing the position you want to access in the middle. So to access the ] field of the first vector position, the num_car position would do:


To show the two values of the first car in the console you can do:

cout<<cars[0].num_car<<" "<<cars[0].tempodevolta;

When you need to go through all you should use a loop / cycle, in which 0 is usually the most appropriate. There are many different ways of doing this for but I will illustrate the most simple and classic:

for (int i = 0; i < cars.size(); i++){
    cout<<cars[i].num_car<<" "<<cars[i].tempodevolta<<endl;

It is important to note that for is based on vector size, calling the for of it. In order to keep everything in line on the screen, I added a size at the end of endl

Example of all this on Ideone


28.10.2017 / 11:14