C++编程 - tuple、any容器

本文介绍了C++中tuple和any容器的应用场景与使用方法。包括如何利用tuple替代struct及实现多值返回,以及使用any创建动态类型的容器。文章还提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++编程 - tuple、any容器


flyfish 2014-10-29


一 tuple
tuple是固定大小的容器,每个元素类型可以不同

作用1 替换struct

struct t1
{
int nID;
double dVal;
};

替换为
typedef std::tuple<int,double> t1;


作用2 任意个数的函数返回值
写法1

std::tuple<int,double> TupleFunction1()
{
	std::tuple<int,double> tupRet(0,0);


	tupRet=std::tuple<int,double>(1,2.1);


	return tupRet;
}


写法2
std::tuple<int,double> TupleFunction2()
{
	return std::make_tuple(1,2.1);
}


调用
auto ret=TupleFunction1();
 std::cout<<std::get<0>(ret)<<" "<<std::get<1>(ret)<< std::endl;

二 any
any容器采用boost库中的any
boost::any  只存储一个任意类型的元素
boost::any a=1;
boost::any b=2.1;

借助any建造一种可以存储任意类型且大小动态变化的容器
	 std::vector<boost::any> v;
	 v.push_back(1);
	 v.push_back(2.1);


输出函数
void OutputAny(boost::any a)
{
	if (!a.empty())
	{
		if(a.type() == typeid(int))
		{
			std::cout<< boost::any_cast<int>(a)<<std::endl;
		}
		if(a.type() == typeid(double))
		{
			std::cout<< boost::any_cast<double>(a)<<std::endl;
		}


	}
}

函数调用
for each(auto e in v)
{
	OutputAny(e);
}




以上程序在Visual C++2010下编译通过

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

二分掌柜的

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值