Controlling a group of objects using STL

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;
}
A vector is the right solution.

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?

Assuming you mean "elements", you can easily store millions of small objects such as instances of your car classes without running into any problems. The number of elements is only limited by available memory and the value returned by the vector member function max_size().
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?

10,000 of your car objects is nothing, but if you approach millions, consider using a deque<car> instead, it's faster to grow.

Alternatively, if you know approximately how many cars you'll have, call vector::reserve() beforehand, so it doesn't have to grow at all.
Thanks for the quick reply @Athar and @Cubbi

I'll see if I manage to integrate vectors into the code.
@Cubbi I missed deques somewhere along my path to learn STL, I'm going to have a look at them now.

Thanks.
Topic archived. No new replies allowed.