C++ pair 和make_pair的用法

原文鏈接:https://blog.csdn.net/weixin_42825576/article/details/81571419

pair 的用法

std::pair主要的作用是將兩個數據組合成一個數據,兩個數據可以是同一類型或者不同類型。
C++標準程序庫中凡是“必須返回兩個值”的函數, 也都會利用pair對象。
class pair可以將兩個值視爲一個單元。容器類別map和multimap就是使用pairs來管理其健值/實值(key/value)的成對元素。
pair被定義爲struct,因此可直接存取pair中的個別值.。
兩個pairs互相比較時, 第一個元素正具有較高的優先級.。

使用案例

vector<pair<int ,int>> dirs;
// 輸入一對座標
dirs.push_back({1, 0});
dirs.push_back({-1, 0});
dirs.push_back(make_pair(0, 1)); // or
dirs.push_back(make_pair(0, -1));
for (auto dir:dirs){
	cout<<dir.first<<dir.second<<endl;
}
// or
for (int i=0;i<dirs.size();i++){
	cout<<dir[i].first<<dir[i].second<<endl;
}

或者也可以這樣創建

vector<pair<int, int>> dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
for (auto dir:dirs){
	cout<<dir.first<<dir.second<<endl;
}
// or
for (int i=0;i<dirs.size();i++){
	cout<<dir[i].first<<dir[i].second<<endl;
}

make_pair的用法

無需寫出型別, 就可以生成一個pair對象
例:
std::make_pair(42, '@');
而不必費力寫成:
std::pair<int, char>(42, '@')

當有必要對一個接受pair參數的函數傳遞兩個值時, make_pair()尤其顯得方便,
void f(std::pair<int, const char*>);

void foo{
f(std::make_pair(42, '@')); //pass two values as pair
}

pair的應用

pair是將2個數據組合成一個數據,當需要這樣的需求時就可以使用pair,如stl中的map就是將key和value放在一起來保存。另一個應用是,當一個函數需要返回2個數據的時候,可以選擇pair。 pair的實現是一個結構體,主要的兩個成員變量是first second 因爲是使用struct不是class,所以可以直接使用pair的成員變量。

make_pair函數

template pair make_pair(T1 a, T2 b) { return pair(a, b); }

很明顯,我們可以使用pair的構造函數也可以使用make_pair來生成我們需要的pair。 一般make_pair都使用在需要pair做參數的位置,可以直接調用make_pair生成pair對象很方便,代碼也很清晰。 另一個使用的方面就是pair可以接受隱式的類型轉換,這樣可以獲得更高的靈活度。靈活度也帶來了一些問題如:

std::pair<int, float>(1, 1.1);

std::make_pair(1, 1.1);

是不同的,第一個就是float,而第2個會自己匹配成double。
make_pair (STL Samples)

Illustrates how to use the make_pair Standard Template Library (STL) function in Visual C++.
template<class first, class second> inline
pair<first,
second> make_pair(
const first& _X,
const second& _Y
)


// mkpair.cpp
// compile with: /EHsc
// Illustrates how to use the make_pair function.
//
// Functions: make_pair - creates an object pair containing two data
// elements of any type.

#include <utility>
#include <iostream>

using namespace std;
/* STL pair data type containing int and float
*/

typedef struct pair<int,float> PAIR_IF;

int main(void)
{
PAIR_IF pair1=make_pair(18,3.14f);
cout << pair1.first << " " << pair1.second << endl;
pair1.first=10;
pair1.second=1.0f;
cout << pair1.first << " " << pair1.second << endl;
}

Output

18 3.14
10 1

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章