C++ 通过迭代器获取集合元素的“索引”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13505562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getting "index" of set element via iterator
提问by user974967
This question applies to both std::set
and std::unsorted_set
.
这个问题适用于std::set
和std::unsorted_set
。
I have an iterator to an element in a set. I'd like to use the iterator to get an "index" for the element based on its location in the set.
我有一个集合中元素的迭代器。我想使用迭代器根据元素在集合中的位置获取元素的“索引”。
For example, the indices for my set would be as follows:
例如,我的集合的索引如下:
int index = 0;
for(MySetType::iterator begin = mySet.begin(); begin != mySet.end(); begin++)
{
cout << "The index for this element is " << index;
index++;
}
I have tried doing arithmetic using iterators but it doesn't work:
我曾尝试使用迭代器进行算术运算,但它不起作用:
int index = mySetIterator - mySet.begin();
Is there any way to use the iterator to get an index value like this based on its location in the set?
有没有办法使用迭代器根据它在集合中的位置来获取这样的索引值?
回答by dreamcrash
STL distanceis what you need. std::distance(set.begin(), find_result)
STL 距离正是您所需要的。std::distance(set.begin(), find_result)
Please note that:
请注意:
"Returns the number of elements between first and last. The behavior is undefinedif last is not reachable from first by (possibly repeatedly) incrementing first. "
“返回第一个和最后一个之间的元素数。如果不能通过(可能重复)首先递增从第一个到达最后一个,则行为未定义。“
Remark : Complexity is linear;
备注:复杂度是线性的;
回答by Hyman
std::set
and set::unordered_set
are associativecontainers, not sequencecontainers, hence the concept itself of index doesn't make much sense.
std::set
并且set::unordered_set
是关联容器,而不是序列容器,因此索引的概念本身没有多大意义。
If you need to retrieve an index for an associative container then design should be changed (even because without a concept of least or most recent inserted element the indices in such containers are subject to change).
如果您需要检索关联容器的索引,则应该更改设计(即使因为没有最少或最近插入元素的概念,此类容器中的索引可能会发生变化)。
回答by moswald
std::set
has just a bidirectional iterator
, which means you can't do what you're trying to do with operator +
(or -
). Those are only available to random access iterators
, like std::vector
provides.
std::set
只有一个bidirectional iterator
,这意味着你不能做你想做的事情operator +
(或-
)。这些仅适用于random access iterators
,例如std::vector
提供。
You need to use std::distance
to get the "index", and std::advance
to move from the beginning of the set to the end.
您需要使用std::distance
来获取“索引”,并std::advance
从集合的开头移动到结尾。
auto distance = std::distance(mySet.begin(), someIterator);
auto it = mySet.begin();
std::advance(it, distance);
assert(it == someIterator);