// 忽略警告
#define _SCL_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#include <assert.h>
#include <iostream>
#include <boost/tuple/tuple.hpp>
#include <boost/ref.hpp>//boost::cref(i)
#include <boost/tuple/tuple_comparison.hpp>// 比较操作
#include <boost/tuple/tuple_io.hpp>// io操作
#include <boost/assign.hpp>
using namespace boost;
using namespace std;
using namespace boost::assign;
template <typename Tuple>
void print_tuple(const Tuple& t)
{
cout << t.get_head() << ',';
print_tuple(t.get_tail());// 递归输出
}
// 用于终止上述的递归输出
void print_tuple(const boost::tuples::null_type& t)
{
cout << endl;
}
int main()
{
// 构造
boost::tuple<int, double> t = boost::make_tuple(2, 3.0);
boost::tuple<int, double> t1 = t;
boost::tuple<float, int, double> t2 = boost::make_tuple(3.5, 3, 2.3);
vector<boost::tuple<int, double, string>> v = assign::tuple_list_of(1, 1.0, "123")(2, 2.0, "456");
v += boost::make_tuple(3, 3.0, "789");
// 引用
int i = 0;
string s = "aaa";
boost::tuple<const int&, string&> tt = boost::make_tuple(boost::cref(i), boost::ref(s));
s += "bbb";
i = 2;
cout << tt.get<0>() << endl;// 访问,<>中为数据位置,2
cout << tt.get<1>().c_str() << endl;//aaabbb
cout << boost::get<1>(tt).c_str() << endl;// aaabbb
assert(t == t1);
//assert(t < t2); // 元素数量不一致
// 错误的遍历方法
//for (int i = 0; i < 2; ++i)
// tt.get<i>();
boost::tuple<int, double, string> myt(1, 2.0, "string");
cout << myt << endl;// (1 2 string)
cin >> myt;// (2 3 asdf ) 必须用() 由于是cin, )前要有一空格
cout << myt << endl;// (2 3 asdf)
cout << boost::tuples::set_open('[') << boost::tuples::set_close(']');
cout << boost::tuples::set_delimiter(',');
cout << myt << endl;// [2,3,asdf]
cout << myt.get_head() << endl;// 得到首元素 2
cout << myt.get_tail() << endl;// 输出剩余元素[3,asdf]
print_tuple(myt);// 2,3,asdf,
// 解包函数tie
int a;
double b;
string c;
boost::tie(a, b, c) = myt;
cout << a << b << c << endl; //23asdf
boost::tie(tuples::ignore, b, tuples::ignore) = myt;// tuples::ignore忽略值
boost::tie(a, b) = make_pair(100, 200.0);
cout << a << b ; //100200
myt.get<1>() = 4;
myt.get<2>() = "wwwwwwwwww";
cout << myt.get<1>() << endl;// 4
cout << myt.get<2>() << endl;// wwwwwwwwww
assert(typeid(int) == typeid(boost::tuples::element<0, boost::tuple<int, double, string>>::type ));// boost::tuple<int, double, string>的第一个元素是int类型
assert(boost::tuples::length<boost::tuple<int, double, string>>::value == 3);// 元素的类型
return 0;
}
来源:CSDN
作者:ztq小天
链接:https://blog.csdn.net/weixin_38850997/article/details/88354142