English 中文(简体)
如何获得元素在集合中的确切位置?
原标题:How to get the exact position of an element in a set?
  • 时间:2010-10-16 21:19:10
  •  标签:
  • c++
  • stl

我有一个<code>std::set<;std::字符串>,我想知道插入后元素在集合中的确切位置。

我尝试了std::distance,但没有任何运气:

#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] << "	" << dist << endl;
    }
    return 0;
}

输出:

zero    0
one     0
one     0
zero    1
two     1
three   1
zero    3

相反,我期待的是:

zero    0
one     1
one     1
zero    0
two     2
three   3
zero    0

有什么想法吗?

最佳回答

它们按字典顺序(基本上按字母顺序)排列。std::set<;的默认比较;T>std::less<;T>,其又调用运算符<

问题回答

首先,字符串是按字典排序的,而不是按它们在英语中表示的数字排序。其次,对于每个元素,在用所有元素完全更新集合之前,代码检查集合中的当前位置。

干杯&;高。,

如上所述,集合通常是用某种树来实现的,它依次存储排序后的数据,而不是按照插入它们的顺序(这使得可以在O(logN)中插入等)。如果你想要你想要的效果,你可以使用任何顺序的容器-矢量,deque,或列表





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?