boost::BOOST_FOREACH

本文深入探讨了C++中的模板元编程,包括如何使用`foreach`、`auto_t`、`assert_t`等关键字进行迭代操作,并通过实例展示了如何注册自定义类类型,以及如何在不同类型集合上进行高效循环处理。文章旨在为读者提供一套简洁高效的编程技巧,助力C++开发者的实践能力提升。
#include "stdafx.h"
#include <string>
#include <iostream>
#include "boost/assign.hpp"
#include "boost/bind.hpp"
#include "boost/typeof/typeof.hpp"
#include "boost/assert.hpp"
#include <boost/foreach.hpp>

#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
#define foreach BOOST_FOREACH
#define auto_t BOOST_AUTO
#define assert_t BOOST_ASSERT

using namespace boost::assign;
using namespace std;

#define BOOST_DISABLE_ASSERTS

struct device
{
device( long LL,string SS,double DD)
:m_id (LL)
,m_name (SS)
,m_double (DD)
{}
long m_id;
string m_name;
double m_double;
};

BOOST_TYPEOF_REGISTER_TYPE(device) //注册一个自定义类 (貌似不注册也行)

int main(int argc, _TCHAR* argv[])
{
//超简洁的循环,且同 const_iterator 同样效果
std::vector<std::vector<int> > g4(3);
foreach( const std::vector<int>& row, g4)
{
//row.push_back(12);

foreach( const int & i,row)
{
//todo
}
}

//对于map 要换成 pair,但不知道为什么不能放到foreach括号中
std::map<int,std::string> M = map_list_of(1,"11") (2,"22") (3,"33");
typedef const pair<int,std::string> ff;
foreach( ff& f,M)
{
cout << f.second ;
}

//对于自定义类型
std::vector<device> G;
device g1(11,"table",2.4);
G.push_back(g1);

foreach(const device & g6,G)
{
cout << g6.m_name ;
}

//没有找到实现 const 的办法,待解决
for ( auto_t( &gg,G.begin()); gg != G.end(); ++gg)
{
cout << gg->m_name ;
}


map<string, vector<device> > vg;
vg.insert(make_pair("name",G));

for ( auto_t( &gg, vg.begin()); gg != vg.end(); ++gg)
{
cout << gg->first ;
}

set<int> s = list_of(10)(20)(30);
BOOST_TYPEOF(*s.begin()) y; //也可以用BOOST_AUTO(y, *s.begin());
foreach(y, s)
{

}

return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值