auto
#include#include using namespace std; int main() { //自动类型推导 auto a = 200; list
lst; lst.push_back(1); lst.push_back(2); lst.push_back(3); //list ::iterator ite = lst.begin(); //根据右边的返回值推导 auto ite = lst.begin(); while (ite != lst.end()) { cout << *ite << endl; ite++; } return 0; } //auto不能出现在函数中 //auto不能作为类中的非静态成员变量 //auto不能定义数组 //auto不能作用于模板参数
for范围
是for循环的一个替代
val相当于arr中的元素
#include#include using namespace std; int main() { int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; for (int i = 0; i < 10; i++) { cout << arr[i] <<" "; } cout << endl; for (int val : arr) { cout << val << " "; } return 0; }
lambda
是一种定义函数的方式
定义函数 返回函数的地址
[]() mutable ->返回值类型{函数体};
#include#include using namespace std; int main() { int a = 10; int b = 20; auto fun = [=]()mutable->int {a = 100; return a + b; }; //[&]和[=]的差别 一个是值传递 一个是引用 引用可以修改实际a的值 而=不能 //加mutable不能改()参数 不加能改 cout< vec1 = { 1,2,3,4,5 }; ::for_each(vec1.begin(), vec1.end(), [](int val) {cout << val << endl; }); return 0; }
智能指针
分为
auto_ptr shared_ptr unique_ptr weak_ptr 其中 在C++11中 auto以弃用
1.shared_ptr:
特点:
定义多个指针可指向同一块空间
初始化方式:
shared_ptr
功能:
2.unique_ptr
特点:
一个指针只能指向一个空间
分别独立
初始化:
unique_ptr
功能
3.weak_ptr 可以看做是shared_ptr的一个工具 辅助作用
特点:
没有*操作和->操作
初始化:
shared_ptr
weak_ptr
功能:
#include#include using namespace std; int main() { //int* p = new int(100); //shared_ptr sp1 (p); //cout << *p << endl; //{ // //shared_ptr sp2(p); // //系统不会识别sp1和sp2是不是指向同一个空间 所以一般我们通过一个智能指针初始化另一个智能指针 // shared_ptr sp2(sp1); // cout << *sp1 << endl; // cout << *sp2 << endl; //} //cout << *p << endl; //shared_ptr sp1(new int (100)); //shared_ptr sp2 = sp1; //cout << *sp1 << endl; //cout << *sp2 << endl; //cout << sp1.get() << endl; //cout << sp2.get() << endl; //sp2.reset(new int(200));//指向新空间 //cout << *sp1 << endl; //cout << *sp2 << endl; //cout << sp1.get() << endl; //cout << sp2.get() << endl; //unique_ptr up1(new int(100)); //int* p1 = up1.get(); //up1.reset(); //指向空 原先的空间被释放 up1.release();指向空 原先的空间不释放 //cout << *p1 << endl; //cout << up1 << endl; shared_ptr sp1(new int(100)); shared_ptr sp2 (sp1); weak_ptr wp(sp2); *wp.lock()=200; cout << *sp2 << endl; cout << wp.use_count() << endl; return 0; }



