赞
踩
在C++中,我们经常会碰到,需要计算两个迭代器之间的距离,例如
set<string> myset;//集合myset中存了一些数
string str;//假定str一定在myset中,求取它的位置
迭代器1:myset.find(str)
迭代器2:myset.begin()
要计算迭代器1与迭代器2之间的距离,由于某些迭代器只支持++和–操作,不支持+和-操作,所以,
这种写法会报错:myset.find(str) - myset.begin()
正确的写法为:int index = distance(myset.begin(), myset.find(str));
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)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。