C++11 (二)

智能指针

#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:
1
0
1
1
0
 */

参考:
慕课郭炜老师CPP程序设计课程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值