【C++标准库】通用工具

Pair

pair将两个value视为一个单元,struct pair定义在头文件<utility>中。

Tuple

tuple扩展了pair的概念,拥有任意数量的元素,位于<tuple>头文件中。

tuple<int, float, string> t1(41, 6.3, "nico");
cout << get<0>(t1) << endl; //41
cout << get<1>(t1) << endl; //6.3
cout << get<2>(t1) << endl; //nico
auto t2 = make_tuple(22, 44, "tom"); //使用make_tuple()创建tuple

 Smart Pointer

所有的smart pointer class都定义在头文件<memory>中

  • shared_ptr 共享式拥有

多个shared_ptr可以共享同一个对象,对象的最末一个拥有者负责销毁对象,并清理与该对象相关的所有资源。

    //方法1
    shared_ptr<string> pNico(new string("nico"));
    //方法2,使用make_shared()
    //shared_ptr<string> pNico = make_shared<string>("nico"); 
    //方法3,先声明shared pointer,再调用reset()赋值
    //shared_ptr<string> pNico;
    //pNico.reset(new string("nico"));
    shared_ptr<string> pJutta(new string("jutta"));
    (*pNico)[0] = 'N';
    pJutta->replace(0, 1,"J");
    vector<shared_ptr<string>> whoMadeCoffee;
    whoMadeCoffee.push_back(pJutta);
    whoMadeCoffee.push_back(pJutta);
    whoMadeCoffee.push_back(pNico);
    whoMadeCoffee.push_back(pJutta);
    whoMadeCoffee.push_back(pNico);

    for (auto ptr : whoMadeCoffee)
    {
        cout << (*ptr) << " ";
    }
    cout << endl;

    (*pNico) = "NicoNew";
    for (auto ptr : whoMadeCoffee)
    {
        cout << (*ptr) << " ";
    }
    cout << endl;

    cout << whoMadeCoffee[0].use_count() << endl; //4
  •  unique_ptr 独占式拥有

unique_ptr不共享它的指针,它无法复制到其他 unique_ptr,无法通过值传递到函数,也无法用于需要副本的任何标准模板库 (STL) 算法。只能移动unique_ptr这意味着,内存资源所有权将转移到另一 unique_ptr,并且原始 unique_ptr 不再拥有此资源。

#include "stdafx.h"
#include <iostream>
#include <memory>

using namespace std;

int main()
{
    unique_ptr<int> pInt(new int(50));
    cout << *pInt << endl;
    return 0;
}

unique_ptr不支持普通的拷贝和赋值操作,但支持一种移动机制来将指针的所有权从一个unique_ptr转移给另一个unique_ptr

unique_ptr<int> pInt(new int(50));
unique_ptr<int> pInt2 = std::move(pInt); //转移所有权
cout << *pInt2 << endl;
//cout << *pInt << endl;  //出错

 数值的极值

定义于<limit>头文件中

#include "stdafx.h"
#include <iostream>
#include <limits>
#include <string>

using namespace std;

int main()
{
    cout << "max(short):" << numeric_limits<short>::max() << endl;
    cout << "max(long):" << numeric_limits<long>::max() << endl;
    return 0;
}

 辅助函数

<algorithm>提供了一些通用工具函数,用来计算最小值和最大值,minmax()返回一个pair<>,其中first为最小值,second为最大值。

#include "stdafx.h"
#include <algorithm>

using namespace std;

bool int_ptr_less(int* a, int* b)
{
    return *a < *b;
}
int main()
{
    int x = 17, y = 42, z = 33;
    int* px = &x;
    int* py = &y;
    int* pz = &z;
    int* pmax = std::max(px, py, int_ptr_less);  //-->42
    std::pair<int*, int*> extremes1 = minmax({ px,py,pz }, int_ptr_less);

    //使用lambda表达式,并使用auto类型推导
    auto extremes2 = std::minmax({ px,py,pz }, [](int* a, int* b) {return *a < *b;});
    return 0;
}
View Code

swap()用于交换两个对象的值,定义于<utility>

原文地址:https://www.cnblogs.com/larry-xia/p/9273557.html