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

来源:互联网 发布:英国本科留学费用 知乎 编辑:程序博客网 时间:2024/05/21 10:48

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 0
原创粉丝点击