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?
Use STL distance, namely
std::distance(set.begin(), mySetIterator)Please note that:
Remark : Complexity is linear;