C++ vector遍历demo,多种姿势任你选~
1.迭代器
1
2
3
4
|
for (vector< int >::iterator it = obj.begin(); it != obj.end(); it++)
{
cout << *it << "," ;
}
|
2.C++11 新增关键字auto
1
2
3
4
|
for (auto it = obj.begin(); it != obj.end(); it++)
{
cout << *it << "," ;
}
|
3.数组遍历法
1
2
3
4
|
for ( int i=0;i<obj.size();i++)
{
cout<<obj[i]<< "," ;
}
|
4.基于范围的for循环
1
2
3
4
|
for (auto iter : obj)
{
cout << iter << "," ;
}
|
demo示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector< int >obj;
for ( int i=0;i<10;i++)
{
obj.push_back(i);
cout<<obj[i]<< "," ;
}
cout << endl << "vector size is :" << obj.size() << endl;
//iterator遍历
for (vector< int >::iterator it = obj.begin(); it != obj.end(); it++)
{
cout << *it << "," ;
}
cout << endl;
//数组循环遍历
for ( int i=0;i<obj.size();i++)
{
cout<<obj[i]<< "," ;
}
cout << endl;
//auto关键字遍历遍历
for (auto it = obj.begin(); it != obj.end(); it++)
{
cout << *it << "," ;
}
cout << endl;
//基于范围的for循环
for (auto iter : obj)
{
cout << iter << "," ;
}
cout << endl;
return 0;
}
|
结果展示:
到此这篇关于C++ vector 遍历的几种方法的文章就介绍到这了,更多相关C++ vector 遍历内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://juejin.cn/post/6988731148788564004