You can use the sorted std::vector<int> . If it is sorted, you can find the element in O(log n) . And you can find the distance in constant time O(1) .
By means of a sorted vector, I mean that after each insertion (or after many insertions) you do std::sort(v.begin(), v.end());
If your type inside std::set<T> not as light as int , you can save both std::set<T> and the sorted vector of iterators std::vector<std::set<T>::iterator> . But it could not be trivial to synchronize these structures. Maybe you can add some position to T ? Or hold std::set<std::pair<T,int>, comp_first_of_pair<T>> , where comp_first_of_pair just has set , sorted only by T , and the second int to save the position in the set?
A few ideas - to even have an O(1) travel time ...
Piotrnycz
source share