I've read a lot about unordered_map (c++11) time-complexity here at stackoverflow, but I haven't found the answer for my question.
Let's assume indexing by integer (just for example):
Insert/at functions work constantly (in average time), so this example would take O(1)
std::unordered_map<int, int> mymap = {
{ 1, 1},
{ 100, 2},
{ 100000, 3 }
};
What I am curious about is how long does it take to iterate through all (unsorted) values stored in map - e.g.
for ( auto it = mymap.begin(); it != mymap.end(); ++it ) { ... }
Can I assume that each stored value is accessed only once (or twice or constant-times)? That would imply that iterate through all values is in N-valued map O(N). The other possibility is that my example with keys {1,10,100000} could take up to 1000000 iteration (if represented by array)
Is there any other container, that can be iterated linearly and value accessed by given key constantly?
What I would really need is (pseudocode)
myStructure.add(key, value) // O(1)
value = myStructure.at(key) // O(1)
for (auto key : mySructure) {...} // O(1) for each key/value pair = O(N) for N values
Is std::unordered_map the structure I need?
Integer indexing is sufficient, average complexity as well.
map
vsunordered_map
should be based on whether you need a relative strict weak ordering of your keys retained. If you do, you need a regularmap
. If you don't,unordered_map
is the most logical choice (provided the keys can be hashed to a reasonable distribution). – WhozCraigmap
orunordered_map
is whether the latter's invalidation of existing iterators/references/pointers duringinsert
/emplace
/[]
triggering rehashing is acceptable, then there're performance differences which tend to be inunordered_map
's favour but should be measured by those whose profilers/instrumentation says must really care.... – Tony Delroy