std :: set中索引处的元素? [英] Element at index in a 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屋!