该问题同时适用于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();
有什么办法根据它在集合中的位置使用迭代器来获取像这样的索引值?
获得两个迭代器之间“距离”的正确方法是['std :: distance'](http://en.cppreference.com/w/cpp/iterator/distance)函数。但是,请在使用前阅读杰克的答案。 –