通过迭代器获取 set 元素的"index"

getting "index" of set element via iterator

本文关键字:index 元素 set 迭代器 获取      更新时间:2023-10-16

这个问题适用于std::setstd::unsorted_set

我有一个集合中元素的迭代器。我想使用迭代器根据元素在集合中的位置获取元素的"索引"。

例如,我的集合的索引如下所示:

int index = 0;
for(MySetType::iterator begin = mySet.begin(); begin != mySet.end(); begin++)
{
    cout << "The index for this element is " << index;
    index++;
}

我尝试使用迭代器进行算术运算,但它不起作用:

int index = mySetIterator - mySet.begin();

有没有办法使用迭代器根据它在集合中的位置来获取这样的索引值?

使用 STL 距离,即std::distance(set.begin(), mySetIterator)

请注意:

返回第一个和最后一个之间的元素数。行为如果无法从第一个到达最后一个,则未定义(可能重复)先递增。

备注:复杂性是线性的;

但是,如果 InputIt 还满足LegacyRandomAccessIterator,复杂性是恒定的。

std::setset::unordered_set关联容器,而不是序列容器,因此索引的概念本身没有多大意义。

如果您需要检索关联容器的索引,则应更改设计(即使没有最小或最近插入元素的概念,此类容器中的索引可能会更改)。

std::set只有一个bidirectional iterator,这意味着你不能做你想用operator +(或-)做的事情。这些只适用于random access iterators,就像std::vector提供的那样。

您需要使用 std::distance 来获取"索引",std::advance从集合的开头移动到末尾。

auto distance = std::distance(mySet.begin(), someIterator);
auto it = mySet.begin();
std::advance(it, distance);
assert(it == someIterator);