gpt4 book ai didi

c++ - std::set 中索引处的元素?

转载 作者:太空宇宙 更新时间:2023-11-04 12:30:27 24 4
gpt4 key购买 nike

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

下面是一个简单的例子:

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

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

最佳答案

它不会导致崩溃,只是无法编译。 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 在边界内。

关于c++ - std::set 中索引处的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58874547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com