建立一對並訪問元素
Pair 允許我們將兩個物件視為一個物件。藉助模板功能 std::make_pair
可以輕鬆構建對。
另一種方法是建立對並稍後分配其元素(first
和 second
)。
#include <iostream>
#include <utility>
int main()
{
std::pair<int,int> p = std::make_pair(1,2); //Creating the pair
std::cout << p.first << " " << p.second << std::endl; //Accessing the elements
//We can also create a pair and assign the elements later
std::pair<int,int> p1;
p1.first = 3;
p1.second = 4;
std::cout << p1.first << " " << p1.second << std::endl;
//We can also create a pair using a constructor
std::pair<int,int> p2 = std::pair<int,int>(5, 6);
std::cout << p2.first << " " << p2.second << std::endl;
return 0;
}