vector容器的三种遍历方法
STL(Standard Template Library)中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; }
二、迭代器遍历
#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函数遍历
#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; }