当前位置:   article > 正文

C++中计算迭代器之间的距离 distance_迭代器距离

迭代器距离

在C++中,我们经常会碰到,需要计算两个迭代器之间的距离,例如

set<string> myset;//集合myset中存了一些数
string str;//假定str一定在myset中,求取它的位置
迭代器1:myset.find(str)
迭代器2:myset.begin()
  • 1
  • 2
  • 3
  • 4

要计算迭代器1与迭代器2之间的距离,由于某些迭代器只支持++和–操作,不支持+和-操作,所以,

这种写法会报错:myset.find(str) - myset.begin()
正确的写法为:int index = distance(myset.begin(), myset.find(str));
  • 1
  • 2

distance(p, q):计算两个迭代器之间的距离,即迭代器 p 经过多少次 + + 操作后和迭代器 q 相等。如果调用时 p 已经指向 q 的后面,则这个函数会返回相应的负距离。

cppreference上的原话为,

Return value
The number of increments needed to go from first to last. The value may be negative if random-access iterators are used and first is reachable from last (since C++11)

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号