Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't unordered_set provide an array access operator

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);
}
like image 742
Homar Avatar asked Apr 10 '15 01:04

Homar


People also ask

What is difference between set and unordered_set?

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).

What does unordered_set find return?

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().

What is the difference between Unordered_map and unordered_set?

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.).

What is the main benefit of using set over unordered_set?

Set allows to traverse elements in sorted order whereas Unordered_set doesn't allow to traverse elements in sorted order.


1 Answers

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());
like image 169
Sergey Kalinichenko Avatar answered Oct 09 '22 06:10

Sergey Kalinichenko