std::pair主要的作用是將兩個數據組合成一個數據,兩個數據可以是同一類型或者不同類型。
例如std::pair<int,float> 或者 std::pair<double,double>等。
pair實質上是一個結構體,其主要的兩個成員變量是first和second,這兩個變量可以直接使用。
初始化一個pair可以使用構造函數,也可以使用std::make_pair函數,make_pair函數的定義如下:
template pair make_pair(T1 a, T2 b) { return pair(a, b); }
一般make_pair都使用在需要pair做參數的位置,可以直接調用make_pair生成pair對象。
另一個使用的方面就是pair可以接受隱式的類型轉換,這樣可以獲得更高的靈活度。但是這樣會出現如下問題:
例如有如下兩個定義:
std::pair<int, float>(1, 1.1);
std::make_pair(1, 1.1);
其中第一個的second變量是float類型,而make_pair函數會將second變量都轉換成double類型。
這個問題在編程是需要引起注意。
下面是一段pair與make_pair的例子程序:
#include <iostream> using namespace std; int main(int argc, char** argv) { pair <string,double> product1 ("tomatoes",3.25); pair <string,double> product2; pair <string,double> product3; product2.first ="lightbulbs"; // type of first is string product2.second =0.99; // type of second is double product3 = make_pair ("shoes",20.0); cout <<"The price of "<< product1.first <<" is $"<< product1.second <<"\n"; cout <<"The price of "<< product2.first <<" is $"<< product2.second <<"\n"; cout <<"The price of "<< product3.first <<" is $"<< product3.second <<"\n"; return 0; }