PDA

View Full Version : What can be the fastest STL container to manage ordered and not-continuos data ?



tonnot
26th September 2011, 08:33
I have a vector<my_structure>. my_structure has an unique id int identifier.
I have :
vector.at(0).id=1;
vector.at(1).id=134;
....
vector.at(200).id=25478;

I use this vector to add, insert, etc...

Now, I need the fastest method to access the data by its id , so I need a method to know that is 25478 is stored at pos 200 .
I could to use a find iterator or maybe to construct a previous 'map' .
What can be the ideal-faster container or method, knowing that I only need to use it as a 'id' finder, not for add or insert or delete data.????
This vector store pen-styles for drawing. For every line I'm going to draw I have to know its style ( by the id ). I'm going to have 'worlds' with more than 100.000 lines.....

Any idea ? Thanks.

Zlatomir
26th September 2011, 08:46
How about replacing the vector with std::map (http://www.cplusplus.com/reference/stl/map/) with the int (id) as key and my_structure value.

tonnot
26th September 2011, 09:09
Thanks Zlato. Yes, I know that possibility.
But, is there any fast alternative to search a value by its id ?( I need only search, not insert and more functionalities)

Thanks again.

FelixB
26th September 2011, 09:26
you have a key (the id) and an associated value (the index). that's exactly whats std::map is for! why do you need an alternative?

stampede
26th September 2011, 09:32
If you chose the std::vector, then to find an element with given id, you can perform a half-interval (binary) search on your vector (I assume that elements in vector are sorted by the id, as in your example). Worst-case performance of binary search is O(log n) - same as find() on std::map (http://www.cplusplus.com/reference/stl/map/find/).
If the values will not be sorted, I suggest using std::map with id as key, because using std::vector, in order to find the given element, you will need to perform linear search on the container ( complexity O(n), its slower than O(log n) ).
To summarize: if elements in vector are sorted by id, use std::vector and binary search. If not, use std::map (if you really care about the find() speed).
---
probably you will get similar results using those two approaches ( you can do some performance tests ), in that case using std::map is far more convenient.