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
wouldn’t just be
vector <configcarros> cars
?– Ricardo Pontual