I think vectors are more efficient than maps in the situation I am using them. They will be loaded once and accessed many times. I was hoping there was a similar way to insert into a vector like you do a map.
Theeper: your statement does not say one way or another whether vector is more efficient than map in your case. Why do you need to store the index of the element as part of the struct?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
struct Stuff {
Stuff() : stuff_id( 0 ), red( 0 ), blue( 0 ), green( 0 ) {}
Stuff( int r, int g, int b, int id = 0 ) : stuff_id( id ), red( r ), green( g ), blue( b ) {}
int stuff_id;
int red;
int green;
int blue;
};
vector<Stuff> vStuff;
vStuff.push_back( Stuff( 0, 0, 255, vStuff.size() ) );
If you are planning to use vector's insert() functions as opposed to vector's push_back() function, then there is absolutely no way vector is a better choice than map, because every insert into a vector that is not at the end incurs a complete reallocation of the underlying array and every element already in the array has to be copied.
As jsmith noted, yes, using insert() for vector is not a good idea if it is to be invoked very frequently.
Unlike the push_back() the insert() may insert a new element at any position in the vector which is very time-intensive and too-much overhead if there are frequent insertions. Coming to performance, worse.
In such case, I would go for std::list that allows to insert anywhere but not much overhead, and better than map and vector.
For better performance and faster search reasons, I would avoid a map in my designs.
maps use hashing technique which is not so recommended option for better performance and duplicate elements.
It would be tricky and not easy to maintain, rather I would use a leaner search method for such faster search and random access.
maps by default use std::less which calls operator< which need not do any hashing at all. In the example above, if ids are at least semi-unique then operator< for Stuff can be implemented to check ids first and in most cases a single integer comparison will be all that is needed, and you won't get any faster than that.