Hello everybody, I'm new here.
I recently learned to use lists as I needed to control a bunch of
objects by iterating through them. I came to the solution myself
although, I'm only halfway there. I managed to create a list of objects
and go through all their variables using a struct but I came onto one
problem.
Mainly when I want to create an object, I'd like to give it a
unique id or name which will be later easy to access through the for loop.
So far I tried to use an array but I'd like to be able to create more objects
during the process running. I know a vector is something I might use but I wanted
to know what you guys think, as I would have to add loads of members to that vector. Would having a 10,000 members in a vector and still adding more have any
bigger impact on the performance, or is it perfectly safe? What do you think?
Here's the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <iostream>
#include <list>
using namespace std;
struct car{
int max_speed;
int id;
};
int main(){
car cars[20];//That's the array used to create the objects
int i;
list<car> carList;
for(i=0;i<20;i++){
cars[i].max_speed=i*10;//It's used here
cars[i].id=i+1;
carList.push_back(cars[i]);
}
list<car>::iterator it;//And it's more or less useless from now on as I'm using the iterator
for(it=carList.begin();it!=carList.end();it++){
car current=*it;
cout << "Car" << current.id << " max. speed: " << current.max_speed << endl;
}
return 0;
}
|