How to get the exact position of an element in a set?
I have a std::set<std::string>
and I want to know the exact position of the element in the set after the insertion.
I tried with std::distance
but without any l开发者_如何学编程uck:
#include <iostream>
#include <string>
#include <set>
#include <iterator>
using namespace std;
int main (int argc, char const *argv[])
{
string array[] = { "zero", "one", "one", "zero", "two", "three", "zero" };
set<string> numbers;
for(size_t i = 0; i < 7; ++i)
{
int dist = distance(numbers.begin(), numbers.insert(array[i]).first);
cout << array[i] << "\t" << dist << endl;
}
return 0;
}
outputs:
zero 0
one 0
one 0
zero 1
two 1
three 1
zero 3
Instead, I was expecting this:
zero 0
one 1
one 1
zero 0
two 2
three 3
zero 0
Any ideas?
They're being sorted lexicographically (basically alphabetically). The default comparison for std::set<T>
is std::less<T>
, which in turn calls operator<
.
First, strings are sorted lexicographically, not on what numbers they denote in English. Secondly, for each element the code checks the current placement in the set, before the set has been fully updated with all elements.
Cheers & hth.,
As said, the set is usually implemented with some sort of a tree, which in turns stores the data sorted, and not in the order you inserted them(which makes it possible to insert etc. in O(logN)). If you want your desired effect, you can use any sequential container - vector, deque, or list
精彩评论