std::set 中索引处的元素?

2022-01-17 00:00:00 set c++ std

我偶然发现了这个问题:我似乎无法在普通 std::set 中选择索引位置处的项目.这是 STD 中的错误吗?

I've stumbled upon this problem: I can't seem to select the item at the index' position in a normal std::set. Is this a bug in STD?

下面是一个简单的例子:

Below a simple example:

#include <iostream>
#include <set>

int main()
{
    std::set<int> my_set;
    my_set.insert(0x4A);
    my_set.insert(0x4F);
    my_set.insert(0x4B);
    my_set.insert(0x45);

    for (std::set<int>::iterator it=my_set.begin(); it!=my_set.end(); ++it)
        std::cout << ' ' << char(*it);  // ups the ordering

    //int x = my_set[0]; // this causes a crash!
}

我能做些什么来解决这个问题?

Anything I can do to fix the issue?

推荐答案

不会导致崩溃,只是无法编译.set 不能通过索引访问.

It doesn't cause a crash, it just doesn't compile. set doesn't have access by index.

你可以像这样得到第n个元素:

You can get the nth element like this:

std::set<int>::iterator it = my_set.begin();
std::advance(it, n);
int x = *it;

假设 my_set.size() >n,当然.您应该知道,此操作所花费的时间大约与 n 成正比.在 C++11 中有一种更好的写法:

Assuming my_set.size() > n, of course. You should be aware that this operation takes time approximately proportional to n. In C++11 there's a nicer way of writing it:

int x = *std::next(my_set.begin(), n);

同样,您必须首先知道 n 在边界内.

Again, you have to know that n is in bounds first.

相关文章