具有示例的C ++ STL向量迭代器
C++STL矢量迭代器
以下是C++STL中的迭代器(公共成员函数),可用于访问元素,
C++STL程序演示矢量迭代器的示例
//C++STL程序演示示例 //向量迭代器 #include <iostream> #include <vector> using namespace std; int main(){ vector<int> v1; v1.push_back(10); v1.push_back(20); v1.push_back(30); v1.push_back(40); v1.push_back(50); //begin()和end()函数 vector<int>::iterator it; it = v1.begin(); cout << "first element is: " << *it << endl; it = v1.end()-1; cout << "last element is: " << *it << endl; //rbegin()和rend()函数 vector<int>::reverse_iterator rit; rit = v1.rbegin(); cout << "first element (from reverse) is: " << *rit << endl; rit = v1.rend()-1; cout << "last element (from reverse) is: " << *rit << endl; //cbegin()和cend()函数 vector<int>::const_iterator cit; cit = v1.cbegin(); cout << "first element is: " << *cit << endl; cit = v1.cend()-1; cout << "last element is: " << *cit << endl; //crbegin()和crend()功能 vector<int>::const_reverse_iterator crit; crit = v1.crbegin(); cout << "first element (from reverse) is: " << *crit << endl; crit = v1.crend()-1; cout << "last element (from reverse) is: " << *crit << endl; return 0; }
输出结果
first element is: 10 last element is: 50 first element (from reverse) is: 50 last element (from reverse) is: 10 first element is: 10 last element is: 50 first element (from reverse) is: 50 last element (from reverse) is: 10