C++11语言新特性
特性1 Range-Based for循环
C++11 引入了一种崭新的 for 循环形式,可以逐一迭代某个给定 的区间、数组、集合(range,array,or collection)内的每一个元素。其他编程语言可能称此为 foreach循环。其一般性语法如下:
#include <iostream>
#include <vector>
using namespace std;
void main(){
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
for (auto v1: v) { //参数1: 形参, 应为参数2中元素类型, 注意: 此处的v1仅为当前正在被处理的元素的拷贝
//若想改动传入的集合的元素, 必须将v1声明为一个非常量的引用&
cout << v1 << endl;
}
for (auto &v1: v) { //为避免调用每个元素的拷贝构造函数和析构函数,可以加引用&
cout << v1 << endl;
}
}
//控制台输出:
/*
1
2
3
4
请按任意键继续. . .
*/
利用template模版类:
#include <iostream>
#include <vector>
using namespace std;
class C {
public:
void m_print() {
cout << "haha" << endl;
}
};
template <typename T>
void printElements(const T& coll) {
//以下两个for循环等价
//for (auto _pos = begin(coll); _pos != end(coll); _pos++) {
for (auto _pos = coll.begin(); _pos != coll.end(); _pos++) {
cout << *_pos << endl;
}
cout << endl;
for (const auto& elem : coll) {
cout << elem << endl;
}
}
void main(){
vector<int> v;
v.emplace_back(1);
v.emplace_back(2);
v.emplace_back(3);
v.emplace_back(4);
printElements(v);
}
/*
控制台输出:
1
2
3
4
1
2
3
4
请按任意键继续. . .
*/