随机访问 的 迭代器 (iterator)

本文通过一个具体的C++ STL示例展示了如何使用迭代器遍历容器,并演示了不同方式访问容器元素的方法,包括使用迭代器、下标运算符及算术运算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//itercat

#include <iostream>
#include <vector>
#include "print_elements.h"
using namespace std;

int main()
{
	vector<int> coll1;

	for(int i = -3;i <= 9; ++i)
	{
		coll1.push_back(i);
	}

	PRINT_ELEMENTS(coll1);

	cout << "number /distance: " << coll1.end() - coll1.begin() <<endl;

	//use operator <
	//list ,set  不能用
	vector<int> ::iterator pos;
	for(pos = coll1.begin(); pos < coll1.end(); ++ pos)
	{
		cout << *pos <<" ";
	}
	cout <<endl;

	//use operator[]
	
	for(int i = 0;i < coll1.size(); ++i)
	{
		cout << coll1.begin()[i] <<" ";
	}
	cout <<endl;
	pos = coll1.begin();
	for(int i = 0;i < coll1.size(); ++i)
	{
		cout << pos[i] << " " ;
	}
	cout <<endl;

	//use +=
	for(pos = coll1.begin(); pos < coll1.end() -1;pos +=2)
	{
		cout << *pos << " " ;
	}
	cout <<endl;
	system("pause");
	return 0;
}


随便写写 stl,例子里写起来真是感到很优美,自己写代码用匈牙利命名法,感觉写不出这种美感 ~~Damn

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值