I need to get the last element from an unordered_set, and it must be using the unordered_set, not any other class. (mostly because I'm to modify lots of code already done) but by what I've been looking the only possible way is iterate over it and save the element and then return it. But in big sets it would be too slow. besides I tried this and did not work.
unordered_set <int>::iterator it = frames.end();
--it;
I got the following error:
"no match for 'operator--' in '--it'"
Its kind of useful mostly because of this, it stores the data in a "stack" way, as following:
unordered_set<int> s;
s.insert(9);
s.insert(4);
s.insert(8);
s.insert(0);
s.insert(1);
unordered_set<int>::iterator it = s.end();
for( it = s.begin(); it!= s.end(); ++it )
cout << *(it) << " ";
it prints:"1 0 8 4 9"
So the "last" element would be always 9, it is the "first" element that was inserted, as I said before in a "stack" way.
Any idea to improve it?
In an unordered_set, the order of inserts does not necessarily correspond to the order that you will get when the set is iterated (hence the name "unordered"). Part of the reason why a bi-directional iterator is not supported(using a -- operator) in this data structure is because being able to go backwards/forwards on an unordered_set makes no difference when you don't know what the order of the elements that you will get out of it.
The order of inserts that you have created does not dictate the order you will get when you iterate (Inserting "9" first doesn't mean s.end() would return a "9"). This is because what dictates that order solely depends on how that set calculates the hash value of each object you insert, similar to a hash table (http://en.wikipedia.org/wiki/Hash_table). Hence, you cannot reliably use this set to replicate a "stack", as this is not what this particular data structure is meant to be used for.
There are other C++ STL data structures that you can use to preserve order such as http://www.cplusplus.com/reference/stack/.