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

Asked

Viewed 2,667 times

7

I would like help to understand how it works to declare a vector of type struct. In the example of the code below I create the struct configcarros and I 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 someone help me understand this ? I’m not finding much researching about struct-like Vectors.

  • 2

    wouldn’t just be vector <configcarros> cars?

1 answer

6


Let me start by saying that, just as @Ricardopunctual indicated in the comments, in C++ you don’t need to include the word struct the use of the structure. In addition, the <vector> something with dynamic size can cut the boot it has, and simplify the statement leaving only:

vector<configcarros> cars;

Insert structures into <vector>

To insert structures into the vector, you can create the structure itself, define its values and add through the method push_back:

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 startup by doing:

configcarros c2{2, 35}; //inicializar logo com os 2 valores
cars.push_back(c2);

Or do everything inline:

cars.push_back(configcarros{5,15});

Read stored structures on <vector>

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

cars[0].num_car

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

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

When you need to traverse all you should use a loop/loop, in which the for is usually the most appropriate. There are many different ways to do this for but I will exemplify the simplest 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 the for is based on the vector size, calling the method size of the same. So that not everything was on the same line on the screen I added a endl at the end of cout

Example of all this in Ideone

Documentation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.