迭代器(c++)

/*#include <iostream>
#include <vector>
using  namespace std;
int main()
{
 vector<int> vecInt;
 vecInt. push_back(1);
 vecInt. push_back(2);
 vecInt.push_back(3);
 int size = vecInt.size();

 vector<int> vecInt2(10);

 vector<int> vecInt3(5, 28);

 vector<int> vecInt4(vecInt3);
 //【,)
 /ector<int> vecInt5(vecInt.begin(), vecInt.begin() + 1);
 vector<int> vecInt5(vecInt.begin(), vecInt.begin() +2);
 vecInt.resize(10);//重新扩充10个数据长度。

 vector.resize(10);// 重新分配10个长度
 return 0;

}*/
//迭代器的几种用法:
#include <iostream>
#include <windows.h>
#include <algorithm>//sort()
#include <vector>
using namespace std;
void printfValue(int& a)
{
 cout << a << endl;
}
bool mySort(int a,int b)
{
 return a > b;//从大到小排序
}
int main()
{  
 vector<int> vecInt3;//就是这样定义容器的。
 vector<int>::iterator itInt;//就是这样定义迭代器的
 itInt = vecInt3.begin(); //第一个元素
 itInt = vecInt3.end();   //从逻辑认为是最后一个元素的下一个
 vecInt3.push_back(1);
 vecInt3.push_back(2);
 vecInt3.push_back(3);
 vecInt3.push_back(4);

 //int num = count(vecInt3.begin(),vecInt3.end(),28);//在vecInt3.begin()到vecInt3.end()范围找28.
 //cout << num<<endl;
 vector<int>::iterator itFind = find(vecInt3.begin(),vecInt3.end(),2);//功能同上,找不到报错
 int a = *itFind;
 cout << a <<endl<<"**************************"<< endl;

 sort(vecInt3.begin(), vecInt3.end(), mySort);//排序函数 (全局的)

 for_each(vecInt3.begin(), vecInt3.end(), printfValue);//在这个区间的数输出
 for (vector<int>::iterator it = vecInt3.begin(); it != vecInt3.end(); it++)// 利用迭代器输出1到4
 {
  cout << *it << endl;//迭代器本身是一个指针
 }
 for (int i = 0; i < vecInt3.size(); i++)// 利用下标输出1到4
 {
  cout << vecInt3[i] << endl;
 }


 vector<int>::const_iterator constIt;
 constIt = vecInt3.begin();

 vector<int>::reverse_iterator rlt;//是一种反向迭代器
 rlt = vecInt3.rend();
 rlt = vecInt3.rbegin();

 getchar();// system("pause");
 return 0;

}

原文地址:https://www.cnblogs.com/rong123/p/7586548.html