std::set 中索引处的元素? [英] Element at index in a std::set?

查看:28
本文介绍了std::set 中索引处的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了这个问题:我似乎无法在普通 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.

这篇关于std::set 中索引处的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆