C++进阶--string类和标准模板库

参考: C++ Primer Plus (第六版)----16章

一.string 类(略)

二. 智能指针

使用智能指针包括三种:auto_ptr、unique_ptr、shared_ptr

智能指针模板都定义了类似指针的对象,可以将new获得的地址赋值给这种对象,当指针过期时,其析构函数将使用delete来释放内存;相比与普通指针,无需再在程序中利用delete释放。

构造函数:

template<class X> 
class auto_ptr
{   
    explicit auto_ptr(X* p = 0) throw(); 
    ...
}

要创建智能指针模板,必须包含头文件 memory,然后使用通常的模板语法来实例化所需类型的指针,如下所示:

auto_ptr<double> pd(new double);
auto_ptr<string> ps(new string);

unique_ptr<double> pdu(new double);
shared_ptr<string> pss(new string);

std::string * ps = new std::string;              //普通指针 创建对象
std::auto_ptr<std::string> ps(new std::string);  //智能指针 创建对象

示例:

// smrtptrs.cpp -- using three kinds of smart pointers
#include <iostream>
#include <string>
#include <memory>

class Report
{
private:
    std::string str;
public:
    Report(const std::string s) : str(s) { std::cout << "Object created!\n"; }
    ~Report() { std::cout << "Object deleted!\n"; }
    void comment() const { std::cout << str << "\n"; }
};

int main()
{
    {
        std::auto_ptr<Report> ps (new Report("using auto_ptr"));
        ps->comment();   // use -> to invoke a member function
    }
    {
        std::shared_ptr<Report> ps (new Report("using shared_ptr"));
        ps->comment();
    }
    {
        std::unique_ptr<Report> ps (new Report("using unique_ptr"));
        ps->comment();
    }
    // std::cin.get();  
    return 0;
}

可以看到,智能指针使用方法与普通指针类似。

选择智能指针:

1. 如果程序要使用多个指向同一个对象的指针,应选择 shared_ptr

2. 如果程序不需要使用多个指向同一个对象的指针,可选择 unique_ptr

三.标准模板库

标准模板库包括:容器、迭代器、函数对象和算法的模板。

1.模板类vector

在头文件 vector 中定义了一个vector模板,要创建模板对象,可使用通常的<type>表示法来指出要使用的类型;

vector 使用动态内存分配,因此可以用初始化参数来指出需要多少矢量;

#include vector
using namespace std;
vector<int> ratings(5); // a vector of 5 ints
int n;
cin >> n;
vector<double> scores(n) // a vector of n doubles

由于运算符 [ ] 被重载,因此创建vector对象后,可以使用通常的数组表示法来访问各个元素:

ratings[0] = 9;
for (int i = 0; i < n; i++)
    cout << scores[i] << endl;

2.可对矢量执行的操作

具体操作方法见书本:

size():返回容器元素数目;

swap():交换两个容器的内容;

begin():返回一个指向容器第一个元素的迭代器(指针);

end():返回一个超过容器尾的迭代器(指针);

push_back():将元素添加到矢量末尾;

erase():删除矢量中给定区间的元素;

insert():插入矢量中给定区间的元素;

...

四.泛函(略)

五.函数对象(略)

六.算法(略)

七.其他库(略)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值