通过迭代器获取 set 元素的"index"
getting "index" of set element via iterator
这个问题适用于std::set
和std::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::set
和set::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);
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 在提升multi_index容器中,是否定义了"default index"?
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将元素添加到数组的线程安全函数?
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 我想访问std::unique_ptr中的一个特定元素
- 如何通过 getter 函数删除矢量的元素?
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 通过迭代器获取 set 元素的"index"