Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting "index" of set element via iterator [duplicate]

Tags:

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?

like image 647
user974967 Avatar asked Nov 22 '12 03:11

user974967


People also ask

Can you index a set in C++?

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.


2 Answers

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.

like image 135
dreamcrash Avatar answered Sep 19 '22 15:09

dreamcrash


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

like image 44
Jack Avatar answered Sep 18 '22 15:09

Jack