I have created a unordered_set with [2,3,5] and I want to access in FIFO order, how it is possible with unordered_set, tried doing this but getting compilation error.
int showFirstUnique() {
if(unique.empty())
return -1;
else{
unordered_set<int> :: iterator itr=unique.end();
itr--;
return *itr;
}
}
Access last element of unordered_set in C++
You can access the last element of unordered associative containers the same way as you can access the last element of forward list: By iterating the elements until you reach it.
The asymptotic complexity of doing this is of course linear, and it is not something that one would typically do with an unordered container.
itr--;
This does not work because unordered container iterators are forward iterators. They cannot be iterated backwards.
I want to access in FIFO order
Elements of unordered containers are not stored in FIFO order. The last element of such container has nothing to do with the order in which the elements were inserted.
You can instead use std::queue
for example to have a FIFO order.