STL 中迭代器的运算
原文:https://www.studytonight.com/cpp/stl/stl-operations-on-iterators
下面是迭代器可以用来执行各种操作的操作。
- 预先的
- 距离
- 然后
- 上一个
- 开始
- 目标
advance()
操作
它会将迭代器 i 增加距离值。如果距离值为负,则迭代器将递减。
语法:advance(iterator i ,int distance)
#include<iostream>
#include<vector>
int main()
{
vector<int> v(10) ; *// create a vector of 10 0's*
vector<int>::iterator **i**; *// defines an iterator i to the vector of integers*
i = v.begin();
*/* i now points to the beginning of the vector v */*
**advance**(i,5);
*/* i now points to the fifth element form the
beginning of the vector v */*
**advance**(i,-1);
*/* i now points to the fourth element from the
beginning of the vector */*
}
distance()
操作
它将返回元素的数量,或者我们可以说第一个迭代器和最后一个迭代器之间的距离。
语法:distance(iterator first, iterator last)
#include<iostream>
#include<vector>
int main()
{
vector<int> v(10) ; *// create a vector of 10 0's*
vector<int>::iterator **i**, **j**; *// defines iterators i,j to the vector of integers*
**i** = v.begin();
*/* i now points to the beginning of the vector v */*
**j** = v.end();
*/* j now points to the end() of the vector v */*
cout << **distance**(i,j) << endl;
*/* prints 10 , */*
}
next()
操作
它会将第 n 个迭代器返回到 i ,即从 I 所指向的元素指向第 n 个元素的迭代器
语法:next(iterator i ,int n)
prev()
操作
它会将第 n 个前置元素返回到 i ,即从 I 所指向的元素指向第 n 个前置元素的迭代器
**语法:prev(iterator i, int n)
begin()
操作
这个方法返回一个迭代器到给定容器的开始。
语法:begin()
end()
操作
这个方法返回一个迭代器到给定容器的末尾。
语法:end()