欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++中的pair使用詳解

 更新時(shí)間:2022年09月06日 14:55:35   作者:Timingup  
pair是定義在<utility>中的生成特定類型的模板,它的作用是把一組數(shù)據(jù)合并為一體,實(shí)際上是一個(gè)擁有兩個(gè)成員變量的struct,這篇文章主要介紹了c++的pair使用,需要的朋友可以參考下

pair是將2個(gè)數(shù)據(jù)組合成一組數(shù)據(jù),當(dāng)需要這樣的需求時(shí)就可以使用pair,如stl中的map就是將key和value放在一起來(lái)保存。另一個(gè)應(yīng)用是,當(dāng)一個(gè)函數(shù)需要返回2個(gè)數(shù)據(jù)的時(shí)候,可以選擇pair。 pair的實(shí)現(xiàn)是一個(gè)結(jié)構(gòu)體,主要的兩個(gè)成員變量是first second 因?yàn)槭鞘褂胹truct不是class,所以可以直接使用pair的成員變量。

下面介紹下C++中的pair使用,內(nèi)容如下所示:

pair基本用法

pair<string, int> p1("hello world", 233);
cout << p1.first << " " << p1.second;

p1 = make_pair("lala", 322);

pair 其他使用

重載pair的加減運(yùn)算符

// 加法
template<class Ty1,class Ty2> 
inline const pair<Ty1,Ty2> operator+(const pair<Ty1, Ty2>&p1, const pair<Ty1, Ty2>&p2)
{
    pair<Ty1, Ty2> ret;
    ret.first = p1.first + p2.first;
    ret.second = p1.second + p2.second;
    return ret;
}

// 減法
template<class Ty1, class Ty2> 
inline const pair<Ty1, Ty2> operator-(const pair<Ty1, Ty2>&p1, const pair<Ty1, Ty2>&p2)
{
    pair<Ty1, Ty2> ret;
    ret.first = p1.first - p2.first;
    ret.second = p1.second - p2.second;
    return ret;
}

在vector中使用

// 初始化舉例
vector<pair<int, int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

// 添加新元素幾種方式
// make_pair
dirs.push_back(make_pair(2,2));
// 初始化構(gòu)造函數(shù)
dirs.push_back(pair<int, int>(2,2));
// 聚合初始化
dirs.push_back({2,2});
// emplace_back
dirs.emplace_back(2,2);

補(bǔ)充:下面看下c++的pair用法

在實(shí)際的工作中,經(jīng)常需要用到pair的內(nèi)容,然后每次呢,我都會(huì)由于忘記pair怎么用的而需要去百度,我個(gè)人覺得很麻煩,于是想著自己總結(jié)一下,這樣,以后看自己寫的也可以更方便直接一點(diǎn)。
因?yàn)橹饕菍懡o自己看的,所以,我將主要以代碼的形式來(lái)展示pair相關(guān)的用法:

#include <iostream>
using namespace std;
int main(){
    std::pair<std::string,int> pr;
    pr.first = "first";
    pr.second = 1;
    std::pair<std::string,int>pr2("second",2);
    std::pair<std::string,int>pr3 = std::make_pair("third",3);
    std::pair<std::string,std::pair<int,float>>pr4=std::make_pair("four",std::make_pair(1,1.0f));

    printf("%-8s:%d\n",pr.first.c_str(),pr.second);
    printf("%-8s:%d\n",pr2.first.c_str(),pr2.second);
    printf("%-8s:%d\n",pr3.first.c_str(),pr3.second);
    printf("%-8s:%d,%.3f\n",pr4.first.c_str(),pr4.second.first,pr4.second.second);

    return 0;
}

輸出結(jié)果如下:

first :1
second :2
third :3
four :1,1.000

到此這篇關(guān)于c++的pair使用詳解的文章就介紹到這了,更多相關(guān)c++ pair使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論