Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
有没有办法确定迭代器在其容器内的位置?我正在寻找的“位置”将采用整数值的形式,它描述了迭代器距容器开头的距离。
例如,vector.front()将是0,并且vector.back()将是vector.size() - 1
vector.front()
0
vector.back()
vector.size() - 1
std::distance:
std::distance
size_t index = std::distance( vector.begin(), it );
它在幕后所做的只是it - v.begin()(对于随机访问迭代器,例如向量)。否则,它只会增加第一个参数,直到它到达第二个(这不是特别有效)。
it - v.begin()