vector容器的三种遍历方法

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

在此表示感谢。

  • 29
    点赞
  • 93
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值