开发者

In C++, how do I get an int index of an iterator?

I need to cout and return a deque e开发者_开发知识库lement's index that an iterator is pointing to. How do I get an int out of an iterator?


You can use:

std::ptrdiff_t index(std::distance(my_container.begin(), my_iterator));

Be aware of the runtime costs of such a routine, however- it depends on the data structure you use.


For random-access iterators you can just use subtraction:

size_t index = some_iterator - some_deque.begin()

Obviously this doesn't work for all iterators (eg. for std::list or whatever) but I'd submit that there's a certain elegance in that you can only use this technique when it'll take constant time. If your container doesn't have random access iterators then it very probably isn't sensible to try to find the index of them anyway.


std::ptrdiff_t index = std::distance(myDeque.begin(), curIterator);


Out of the two presented methods:

std::ptrdiff_t index(std::distance(my_container.begin(), my_iterator));

and

std::ptrdiff_t index = some_iterator - some_deque.begin()

... the latter has the superiority of being only applicable to random access iterators -- hence when substituting for another container, you wont accidentaly get an expensive operation (O(n) for lists for example).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜