STL 中的元组

原文:https://www.studytonight.com/cpp/stl/stl-tuple-template

tuplepair的结构非常相似。就像配对一样,我们可以配对两个异构对象,在元组中,我们可以配对三个异构对象。

元组的语法是:

// creates tuple of three object of type T1, T2 and T3
tuple<T1, T2, T3> tuple1;

Tuple Template


元组模板:一些常用函数

与 pair 类似,tuple 模板有自己的成员和非成员函数,下面列出了其中的一些函数:

  • 构造新元组的构造器
  • 运算符 = :为元组赋值
  • 交换:交换二元组的值
  • make_tuple():创建并返回一个包含由参数列表描述的元素的元组。
  • 运算符(==,!=,>,< , <= , > =):按字典顺序比较两对。
  • 元组元素:返回元组元素的类型
  • 联系:将元组的值与其引用联系起来。

演示元组模板的程序

#include <iostream>

int main ()
{
   tuple<int, int, int> tuple1;   //creates tuple of integers
   tuple<int, string, string> tuple2;    // creates pair of an integer an 2 string

   tuple1 = make_tuple(1,2,3);  // insert 1, 2 and 3 to the tuple1
   tuple2 = make_pair(1,"Studytonight", "Loves You");
   /* insert 1, "Studytonight" and "Loves You" in tuple2  */

   int id;
   string first_name, last_name;

   tie(id,first_name,last_name) = tuple2;
   /* ties id, first_name, last_name to 
   first, second and third element of tuple2 */

   cout << id <<" "<< first_name <<" "<< last_name;
   /* prints 1 Studytonight Loves You  */

   return 0;
}