1.C++11的新标准提供了一种新的遍历方式:
即
for(<T>element : vector)
{
//option
}
等价于原来的for (int i = 0; i < vector.size(); i++)
{
//option
}
恩,感觉省事了不少!
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//遍历数组
int a[10] = {0};
for(int num :a)
{
cout<<num<<endl;
}
cout<<endl;
//遍历容器类
vector <int> b;
b.push_back(1);
b.push_back(2);
for (int num : b)
{
cout<<num<<endl;
}
getchar();
return 0;
}
上述方法可以遍历的对象包括:(1).数组。(不包括指针)
(2).定义了begin()和end()方法,且返回该方法返回迭代器的类对象。(STL 中所有容器都可以)
但是想要改变其中的值的时候却出了问题:
int _tmain(int argc, _TCHAR* argv[])
{
//遍历数组
int a[10] = {0};
//更改数组中的值
for (int num : a)
{
num = 2;
}
//输出
for(int num :a)
{
cout<<num<<endl;
}
cout<<endl;
getchar();
return 0;
上面的代码输出还是0。
原因是参数传递的时候,使用的是值传递,更改只限于函数内部。
要想使修改真正作用到参数本身,需要用引用传递:
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//遍历数组
int a[10] = {0};
//更改数组中的值
for (int &num : a)
{
num = 2;
}
//输出
for(int num :a)
{
cout<<num<<endl;
}
cout<<endl;
getchar();
return 0;
}
这样结果就是2了。
2.vector可以保存对象,包括vector,但是不能保存引用。引用只是对象的别名。
使用vector的时候,循环时不能更改vector的大小。
使用vector时,下标只是用来访问已存在的元素的,不能用来初始化。
3.迭代器的使用
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector <int> v;
v.push_back(1);
v.push_back(2);
vector<int>::iterator it;
for (it = v.begin();it != v.end();it++)
{
cout<<(*it)<<endl;
}
getchar();
return 0;
}