这个问题适用于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++;
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用迭代器进行算术运算,但它不起作用:
int index = mySetIterator - mySet.begin();
Run Code Online (Sandbox Code Playgroud)
有没有办法使用迭代器根据它在集合中的位置获取这样的索引值?
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25091 次 |
| 最近记录: |