在c98中,不同的容器和数组,遍历的方法不尽相同,写法不统一。
c++11基于范围的for循环以统一,简洁的方式来遍历容器和数组,用起来更方便了。
c++标准库里的容器:
#include<array> 数组容器
#include<vector> 向量容器,顺序表容器
#include<list> 双链表容器
#include<map> 映射容器(底层是红黑树)
#include<set> 关联容器(底层是红黑树)
无序容器
#include<unordered_map>
#include<unordered_set>
在c++中遍历一个数组或容器的一般方法:
int main()
{
int ar[] = { 1,2,3,4,5,6 };
int n = sizeof(ar)/sizeof(ar[0]);
int* ip = NULL;
for (int i = 0; i < n; ++ip)
{
cout << ar[i] << " ";
}
for (ip = ar; ip != ar + n; ++ip)
{
cout << *ip << " ";
}
cout << endl;
return 0;
}
在c++11基于范围的for循环
int main()
{
int ar[] = { 1,2,3,4,5,6 };
for (int x : ar)
{
cout << x << " ";
}
cout << endl;
return 0;
}
基于范围的for循环的一般格式:
for (ElemType val : array)
{
....//statement循环体
}
ElemType:是范围变量的数据类型。
它必须与数组(容器)元素的数据类型一样,或者是数组元素可以自动转换过来的类型。
val :是范围变量的名称。
该变量将在循环迭代期间依次接收数组中的元素值。在第一次循环迭代期间,它接收的是第一个元素的值;在第二次循环迭代期间,它接收的是第二个元素的值;以此类推。
array:是要让该循环进行处理的数组(容器)的名称。
该循环将对数组中的每个元素迭代一次。
statement:是在每次循环迭代期间要执行的语句。
要在循环中执行更多的语句,则可以使用一组大括号来包围多个语句。与其他循环体一样,可以用continue来结束本次循环,也可以用break来跳出整个循环。
一般的for循环可以任意按想法遍历,基于范围的for必须依次遍历(不能控制像奇数遍历,偶数遍历这种,但可以在循环体中break跳出停止循环)
for (ElemType val : array)这个必须按格式来写,循环体可以按自己想法来写。
使用auto自动推导出val的数据类型
auto 的使用方法详见:C11的新特性-auto关键字,decltype关键字_♚陌上花开的博客-CSDN博客http://t.csdn.cn/FHL89http://t.csdn.cn/FHL89
int main()
{
int ar[] = { 1,2,3,4,5 };
for (auto x : ar)
{
cout << x << " ";
}
cout << endl;
for (auto& x : ar)//此处引用,每一次循环都会给x一个新的引用,第一次的x引用第一个值,第二个x引用第二个值...
{
x += 10;
cout << x << " ";
}
return 0;
}
#include<iostream>
using namespace std;
struct Student
{
char s_id[20];
char s_name[20];
char s_sex[10];
int s_age;
};
int main()
{
struct Student dx[] = { {"12201","zyt","man",17},{"12202","zzyt","man",18} };
for (const auto &x: dx)//const只读不写,不会改变原有的值,&,提高效率
{
//auto可以自己推导出x的类型,就很方便
cout << x.s_age << " ";
cout << x.s_id << " ";
cout << x.s_name << " ";
cout << x.s_sex << " ";
}
return 0;
}
void PrintAr(auto& br)//类似于模板
{
for (const auto& x : br)//使用auto 可以自己推导类型
{
cout << x << " ";
}
cout << endl;
}
int main()
{
int ar[] = { 1,2,3,4,5,6 };
double dx[] = { 1.2,2.3,3,4,4.5,5.6,6.7 };
PrintAr(ar);
PrintAr(dx);
return 0;
}