C++容器元素遍历的问题

C++容器遍历可以用容器的迭代器来完成,但是像vector、dequeue等线性容器可以用[]来索引,迭代方式如下:

#include<iostream>
#include<vector>
using namespace std;

int main()  
{  
	vector<int> temp(10,1);
	//有警告:unsigned int和int不匹配
	for(int i=0;i<temp.size();i++)
		cout<<temp[i]<<endl;
	//无警告
	for(unsigned int i=0;i<temp.size();i++)
		cout<<temp[i]<<endl;
	for(size_t i=0;i<temp.size();i++)
		cout<<temp[i]<<endl;
	for(auto iter=temp.begin();iter!=temp.end();iter++)
		cout<<*iter<<endl;
<pre name="code" class="cpp"><span style="white-space:pre">	</span>
for(auto iter=temp.begin();iter!=next(temp.begin(),10);iter++)cout<<*iter<<endl;
<span>	</span>
<span style="white-space:pre">	</span>for(int i=0;i<int(temp.size()-5);i++)
		cout<<temp[i]<<endl;
system("pause"); return 0; }

 
其中第一循环使有警告的,这个时候可以用第二个和第三个循环的办法把警告去掉,第四种循环用了迭代器,第五种中的next,还有类似的prev函数,返回输入迭代器,表示第一个迭代器后面/前面k个位置的迭代器。 

注意一点:当for循环中存在比较时,必须把无符号数转换成有符号数进行比较,即只能用最后一种循环,因为如果无符号数相减,只能得到正数,如1-2=4294967295,而不是-1,当需要有负数时,就只能考虑最后一种循环了。

#include<iostream>
using namespace std;

int main()  
{  
	unsigned int a=1,b=2;
	cout<<a-b<<endl;

    system("pause");  
    return 0;  
}
结果:4294967295



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值