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

新手上路,请多包涵

我偶然发现了这个问题:我似乎无法在正常的 std::set 中选择索引位置的项目。这是性病中的错误吗?

下面是一个简单的例子:

 #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!
}

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

原文由 hauron 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

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

您可以像这样获得第 n 个元素:

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

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

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

同样,您必须知道 n 首先是在界限内。

原文由 Steve Jessop 发布,翻译遵循 CC BY-SA 3.0 许可协议

我相信最优化的方法,特别是如果这个索引发生在一个循环中,是转换为一个向量。

 auto my_vect = std::vector(my_set.begin(), my_set.end()); // O[n]
int output = my_vect[n]; // O[1]

原文由 dewe 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题