Another way to implement this is map instead of vector . I will show you this approach and discuss the differences:
Just create a class that has two maps behind the scenes.
#include <map> #include <string> using namespace std; class SpecialMap { // usual stuff... private: int counter_; map<int, string> insertion_order_; map<string, int> data_; };
Then you can set the iterator for the iterator over data_ in the correct order. How do you do this, iterate through insertion_order_ , and for each element that you get from this iteration, do a search in data_ with a value from insertion_order_
You can use the more efficient hash_map for insertion_order, since you do not need to iterate directly through insertion_order_ .
To make inserts, you might have a method like this:
void SpecialMap::Insert(const string& key, int value) {
There are many ways to improve design and worry about performance, but this is a good skeleton to get you started using this functionality yourself. You can make it a template, and you can actually store the pairs as values ββin data_, so that you can easily reference the entry in insertion_order_. But I leave these design problems as an exercise :-).
Update . I suppose I have to say something about the efficiency of using map vs. vector for insertion_order _
- search directly in data, in both cases O (1)
- The insertion in the vector approach is O (1), the insertion in the approach to the map is O (logn)
- deletes O (n) in the vector approach because you need to scan the item for deletion. Using the map approach, they are equal to O (logn).
Perhaps if you are not going to use the removal as much, you should use a vector approach. A card-based approach would be better if you maintained a different order (for example, priority) instead of the placement order.
Tom Jul 08 '09 at 16:57 2009-07-08 16:57
source share