I'm curious as to why the STL container unordered_set
, which has constant time complexity for random access on average, does not provide a method for accessing elements by some distance from the first element in the container. For example:
T& unordered_set::operator[](size_t index)
{
return *(begin() + index);
}
Set is an ordered sequence of unique keys whereas unordered_set is a set in which key can be stored in any order, so unordered. Set is implemented as a balanced tree structure that is why it is possible to maintain order between the elements (by specific tree traversal).
The unordered_set::find() function is a built-in function in C++ STL which is used to search for an element in the container. It returns an iterator to the element, if found else, it returns an iterator pointing to unordered_set::end().
The difference between an unordered_map and an unordered_set is that an unordered_map stores data only in the form of key-value pair while an unordered_set can store data that is not necessarily in the form of key-value pairs (example integer, string, etc.).
Set allows to traverse elements in sorted order whereas Unordered_set doesn't allow to traverse elements in sorted order.
Accessing an element "by some distance" implies that there is some meaningful way to measure that distance. The trouble with std::unordered_set
is that is is, well, unordered. Hence, there is no meaningful way of explaining "some distance from the beginning" in a non-arbitrary way.
If you want to access by distance, copy the data into a vector:
std::vector tmp(unordered.begin(), unordered.end());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With