STL(Standard Template Library)中vector容器是最常见的容器之一,设计中经常需要遍历vector容器,本文介绍三种常用的vector遍历方式。
一、下标索引遍历
vector容器底层其实是动态数组的包装,因此在其内部重载了[]运算符。
函数原型如下:
因此可以采用访问数组元素的类似方式访问vector内部的元素。
示例代码:
// vector容器遍历方式1 —— 下标遍历
void traverseVector_1(vector<int> v)
{
for(unsigned int i = 0; i < v.size(); ++i)
{
cout<<v[i]<<" ";
}
cout<<endl;
}
二、迭代器遍历
与数组元素的指针访问方式类似,vector的第二种遍历方式是采用迭代器(iterator 智能指针的一种)。
【迭代器的底层是对原生指针的封装】
示例代码:
#include <iostream>
#include <vector>
using namespace std;
// vector容器遍历方式2 —— 迭代器遍历
void traverseVector_2(vector<int> v)
{
// 注:如果参数为const vector<int> 需要用const_iterator
vector<int>::iterator it = v.begin();
// vector<int>::const_iterator iter=v.begin();
for(; it != v.end(); ++it)
{
cout<<(*it)<<" ";
}
cout<<endl;
}
三、copy函数遍历
vector第三种遍历方式是采用泛型算法中的copy函数【内部是模板函数】
大致看一下其内部实现:
调用copy函数的大致格式为 copy(begin, end, it);
第三个参数为一个迭代器,遍历vector时可以使用 输出流迭代器 ostream_iterator
示例代码:
#include <iostream>
#include <vector>
using namespace std;
// vector容器遍历方式3 —— cpoy函数遍历
void traverseVector_3(vector<int> v)
{
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " ") );
cout<<endl;
}
转自:
http://www.tuicool.com/articles/yUfQFnA
在此表示感谢。