C++11 (二)
来源:互联网 发布:矩阵相加 编辑:程序博客网 时间:2024/06/14 01:56
智能指针
#include<memory>#include<iostream>using namespace std;/* * 多个share_ptr对象可以同时托管一个指针,系统会维护一个 * 托管计数,当无share_ptr托管指针时,delete该指针 * * 注意:share_ptr对象不能托管指向动态分配的数组额指针 */struct A{ int n; A(int v=0):n(v){} ~A(){cout<<n<<" destructor"<<endl;}};int main(){ shared_ptr<A> sp1(new A(2)); shared_ptr<A> sp2(sp1); cout<<"1)"<<sp1->n<<","<<sp2->n<<endl; shared_ptr<A> sp3; A*p=sp1.get(); cout<<"2)"<<p->n<<endl; sp3=sp1; cout<<"3)"<<(*sp3).n<<endl; sp1.reset(); if(!sp1) cout<<"4)sp1 is null"<<endl; A *q=new A(3); sp1.reset(q); cout<<"5)"<<sp1->n<<endl; shared_ptr<A>sp4(sp1); shared_ptr<A>sp5; //sp5.reset(q); 不妥,会导致程序出错 sp1.reset(); cout<<"before end mian"<<endl; sp4.reset(); cout<<"end mian"<<endl; return 0;}
成员变量默认初始值
#include<iostream>using namespace std;/* * 成员变量默认初始值 */class B{public: int m=1234; int n;};int main(){ B b; cout<<b.m<<endl; return 0;}
nullptr
#include<iostream>#include<memory>using namespace std;/* * * nullptr */int main(){ int *p1=NULL; int *p2= nullptr; shared_ptr<double >p3= nullptr; if(p1==p2) cout<<"equal 1"<<endl; if(p3== nullptr) cout<<"equal 2"<<endl; if(p3==NULL) cout<<"equal 4"<<endl; /* bool b= nullptr; cout<<b<<endl; ??编译出错 gcc 4.7.1 //int i=nullptr; */ return 0;}
哈希表
#include<iostream>#include<string>#include<unordered_map>using namespace std;/* * 无序容器(哈希表) * 操作与map相同,内存占用多 * 哈希表的插入和查询的时间复杂度几乎是常数 */int main(){ unordered_map<string,int> turingWinner; turingWinner.insert({"Dijkstra",1972}); turingWinner.insert({"Scott",1976}); turingWinner.insert({"Wilkes",1967}); turingWinner.insert({"Hamming",1968}); turingWinner["Ritche"]=1983; string name; cin>>name; auto p=turingWinner.find(name); if(p!=turingWinner.end()) cout<<p->second; else cout<<"Not Found"<<endl; return 0;}
正则式
#include<iostream>#include<regex>using namespace std;/* * 正则表达式 * regex_match 输出0,匹配失败 * \\1 表示疑问 */int main(){ regex reg("b.?p.*k"); cout<<regex_match("bopggk",reg)<<endl; cout<<regex_match("boopgggk",reg)<<endl; cout<<regex_match("b pk",reg)<<endl; regex reg2("\\d{3}([a-zA-Z]+).(\\d{2}|N/A)\\s\\1"); string correct="123Hello N/A Hello"; string incorrect="123Hello 12 hello"; cout<<regex_match(correct,reg2)<<endl; cout<<regex_match(incorrect,reg2)<<endl; return 0;}/*output:10110 */
参考:
慕课郭炜老师CPP程序设计课程
0 0
- c/c++(二)
- C实现C(二)
- 《展现 C#》(二)
- C#讲义(二)
- C陷阱(二)
- oj(二)c
- C语言(二)
- Unix C (二)
- mdev.c(二)
- C练习(二)
- C++--开始(二)
- 《Effective C++》(二)
- C#(二)总结
- utilities(C/C++)(二)
- [C#]c#面试笔试题(二)
- 从C到C++(二)
- C语言库函数(二)
- 程序积累二(C)
- Git Merge
- Collection之List方法和分类
- 模板学习笔记2
- 解读 RtlConvertNtFilePathToWin32FilePath
- 浅析this指针
- C++11 (二)
- nginx配置笔记
- 如何安装SQL Server 2008数据库(带完整图解)
- Struts2中的拦截器interceptor
- openlayers3.14源码学习(1)
- 2python机器学习--SVM(决策树分类算法)
- Hash Function 哈希函数
- 大鱼后传
- 最长递减子序列