c++ - 通过迭代器获取集合元素的 "index"

标签 c++ stl iterator

<分区>

这个问题适用于 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 distance ,即 std::distance(set.begin(), mySetIterator)

请注意:

Returns the number of elements between first and last. The behavior is undefined if last is not reachable from first by (possibly repeatedly) incrementing first.

备注:复杂度是线性的;

However, if InputIt additionally meets the requirements of LegacyRandomAccessIterator, complexity is constant.

关于c++ - 通过迭代器获取集合元素的 "index",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13505562/

相关文章:

c++ - OpenCV 中的自定义 SIFT 检测器

php - 将 RecursiveIteratorIterator 与命名空间一起使用?

c++ - 我如何使用注册表?

c++ - 用 C++ 控制现有的 Internet Explorer

c++ - 为什么取消引用指向 std::set 的提取节点的指针是未定义的行为?

C++ - 返回 const 对象的 const vector 的 const vector

c++ - 为什么不能将 C++ 设置迭代器强制转换为 boolean 值?

c++ - 映射、迭代器和复杂结构 - STL 错误

rust - 我如何应对惰性迭代器?

php - 有没有办法在 php 中使用 C++/C 甚至 python