tags:

views:

63

answers:

3

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 luck:

#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?

A: 

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

Alf P. Steinbach
+5  A: 

They're being sorted lexicographically (basically alphabetically). The default comparison for std::set<T> is std::less<T>, which in turn calls operator<.

Oli Charlesworth
A: 

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

Armen Tsirunyan