tuple容器(元組), 是表示元組容器, 是不包含任何結構的,快速而低質(粗制濫造, quick and dirty)的, 可以用於函數返回多個返回值;
tuple容器, 可以使用直接初始化, 和"make_tuple()"初始化, 訪問元素使用"get<>()"方法, 注意get裡面的位置信息, 必須是常量表達式(const expression);
可以通過"std::tuple_size<decltype(t)>::value"獲取元素數量; "std::tuple_element<0, decltype(t)>::type"獲取元素類型;
如果tuple類型進行比較, 則需要保持元素數量相同, 類型可以比較, 如相同類型, 或可以相互轉換類型(int&double);
無法通過普通的方法遍歷tuple容器, 因為"get<>()"方法, 無法使用變量獲取值;
以下代碼包含一些基本的用法, 詳見注釋;
代碼:
/*
* CppPrimer.cpp
*
* Created on: 2013.12.9
* Author: Caroline
*/
/*eclipse cdt, gcc 4.8.1*/
#include <iostream>
#include <vector>
#include <string>
#include <tuple>
using namespace std;
std::tuple<std::string, int>
giveName(void)
{
std::string cw("Caroline");
int a(2013);
std::tuple<std::string, int> t = std::make_tuple(cw, a);
return t;
}
int main()
{
std::tuple<int, double, std::string> t(64, 128.0, "Caroline");
std::tuple<std::string, std::string, int> t2 =
std::make_tuple("Caroline", "Wendy", 1992);
//返回元素個數
size_t num = std::tuple_size<decltype(t)>::value;
std::cout << "num = " << num << std::endl;
//獲取第1個值的元素類型
std::tuple_element<1, decltype(t)>::type cnt = std::get<1>(t);
std::cout << "cnt = " << cnt << std::endl;
//比較
std::tuple<int, int> ti(24, 48);
std::tuple<double, double> td(28.0, 56.0);
bool b = (ti < td);
std::cout << "b = " << b << std::endl;
//tuple作為返回值
auto a = giveName();
std::cout << "name: " << get<0>(a)
<< " years: " << get<1>(a) << std::endl;
return 0;
}
輸出:
num = 3 cnt = 128 b = 1 name: Caroline years: 2013
作者:csdn博客 Spike_King