This question applies to both std::set
and std::unsorted_set
.
I have an iterator to an element in a set. I'd like to use the iterator to get an "index" for the element based on its location in the set.
For example, the indices for my set would be as follows:
int index = 0; for(MySetType::iterator begin = mySet.begin(); begin != mySet.end(); begin++) { cout << "The index for this element is " << index; index++; }
I have tried doing arithmetic using iterators but it doesn't work:
int index = mySetIterator - mySet.begin();
Is there any way to use the iterator to get an index value like this based on its location in the set?
A set in c++ is an associative(STL) container used to store unique elements, and they are stored in a specific sorted order(increasing or decreasing). Elements of the set are unique, i.e., no duplicate values can be stored in the set because each value in the set is a key, and the set doesn't support indexing.
Use STL distance, namely std::distance(set.begin(), mySetIterator)
Please note that:
Returns the number of elements between first and last. The behavior is undefined if last is not reachable from first by (possibly repeatedly) incrementing first.
Remark : Complexity is linear;
However, if InputIt additionally meets the requirements of LegacyRandomAccessIterator, complexity is constant.
std::set
and set::unordered_set
are associative containers, not sequence containers, hence the concept itself of index doesn't make much sense.
If you need to retrieve an index for an associative container then design should be changed (even because without a concept of least or most recent inserted element the indices in such containers are subject to change).
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