Boost Assign
用来方便的对 stl容器 填充数据.
例子1:
#include <boost/assign/std/vector.hpp> // for 'operator+=()'
#include <boost/assert.hpp>;
using namespace std;
using namespace boost::assign;
vector<int> values;
values += 1,2,3,4,5,6,7,8,9; //把这些数据添加到 values 末尾.
例子2:
#include <boost/assign/list_inserter.hpp> // for 'insert()'
#include <boost/assert.hpp>
#include <string>
using namespace std;
using namespace boost::assign; // bring 'insert()' into scope
map<string,int> months;
insert( months )
( "january", 31 )( "february", 28 )
( "march", 31 )( "april", 30 )
( "may", 31 )( "june", 30 )
( "july", 31 )( "august", 31 )
( "september", 30 )( "october", 31 )
( "november", 30 )( "december", 31 ); //插入
deque<int> di;
push_front( di ) = 1,2,3,4,5,6,7,8,9; //插入
例子3:
list_of() 的使用
它用来创建一个匿名的序列. 这个列表可以被自动转换为任何容器.
#include <boost/assign/list_of.hpp> // for 'list_of()' #include <list> #include <stack> #include <string> using namespace std; using namespace boost::assign; // bring 'list_of()' into scope //初始化容器 const list<int> primes = list_of(1)(2)(3)(5)(7)(11);
//初始化 容器适配器. 要注意要多一个 .toadapter() 调用. const stack<string> names = list_of( "Mr. Foo" )( "Mr. Bar")( "Mrs. FooBar" ).to_adapter();
// 对 map 要用 map_list_of() 来构造匿名序列.
map<int,int> next = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6);
例子4:
repeat()
repeat_fun()
用来做重复的插入. 如下例:
vector<int> v;
v += 1,2,3,repeat(10,4),5,6,7,8,9;
// v = [1,2,3,4,4,4,4,4,4,4,4,4,4,5,6,7,8,9]
v += 1,2,repeat_fun(4,&rand),4; //repeat_fun()的第2个参数要求一个无参函数. 用该函数的返回值填充.
// v = [1,2,?,?,?,?,4]