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
原创粉丝点击