C++中pair将2个数据组合成一个数据,在boost中Boost.tuple库支持该功能,且支持使用三元组、四元组和更大的类型集合。
std::tuple是C++ 11中引入的一个非常有用的结构,之前要返回一个包含不同数据类型的返回值,一般都需要自定义一个结构体或者通过函数的参数来返回,现在std::tuple可以实现该功能。
代码
// An highlighted block
#include "stdafx.h"
#include <string>
#include <iostream>
#include <boost/tuple/tuple.hpp>
boost::tuple<int ,std::string> almost_a_pair(10,"Tian");
boost::tuple<int ,float,double,int> quad(10,1.98,23.90,1);
int _tmain(int argc, _TCHAR* argv[])
{
//通过boost::get<n>()函数获取值,n为从零开始索引
int iPos = boost::get<0>(almost_a_pair);
const std::string &str = boost::get<1>(almost_a_pair);
std::cout<<iPos<<" "<<str<<std::endl;
std::cout<<boost::get<0>(quad)<<" "<<
boost::get<1>(quad)<<" "<<
boost::get<2>(quad)<<" "<<
boost::get<3>(quad)<<" "<<std::endl;
//boost::make_tuple()函数构造元组
/*
std::set<boost::tuple<int , double , std::string>> s_tuple;
s_tuple.insert(boost::make_tuple(1 , 2,4 , "Duck"));
s_tuple.insert(boost::make_tuple(2 , 3,5 , "Link"));
s_tuple.insert(boost::make_tuple(3 , 4,8 , "Layer"));
auto t = make_tuple(1 , 2.0 , 3);
assert( 3 == boost::get<2>(t));
*/
//另外一种方式获取tuple中的值
int i = 0 , j = 0;
float f = 0.00;
double d = 0.00;
boost::tie(i,f,d,j) = quad;
return 0;
}