C++程式實現STL中的對


pair是一個簡單的容器,它由兩個資料物件組成

‘first’ = The first element is referenced as ‘first’
‘second’ = the second element and the order is fixed (first, second).

pair可以被賦值、比較和複製。它常用於把可能型別不同的兩個值組合在一起。

語法是: pair<資料型別1, 資料型別2>變數名(資料值1, 資料值2)。

演算法

Begin
   Write pair<data type1,data type 2>variable name(datavalue1,datavalue2)
   Print the pairs
End

示例程式碼

#include<iostream>
using namespace std;
int main() {
   pair <char,int> value('a',7);
   pair <string,double> fruit ("grapes",2.30);
   pair <string,double> food ("pulao",200);
   cout<<"The value of "<<value.first<<" is "<<value.second <<endl;
   cout<<"The price of "<<fruit.first<<" is Rs. "<<fruit.second <<endl;
   cout<<"The price of "<<food.first<<" is Rs. "<<food.second <<endl;
   return 0;
}

輸出

The value of a is 7
The price of grapes is Rs. 2.3
The price of pulao is Rs. 200

更新於: 2019-07-30

287次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.