boost::assign通过对"+="和","的重载非常方便的填充标准容器(std::vector,std::set,std::list,std::map),使用boost::assign需要#include<boost/assign.hpp>
1.使用boost::assign对标准容器插入数据
int main(){ using namespace boost::assign; //对std::vector std::vector<int> v; v+=1,3,6,7,9,5,8,9,1,63; //对std::set std::set<std::string> s; s+="test","for","boost::assign"; //对std::map std::map<int,std::string> mp; mp+=std::make_pair(0,"test"),std::make_pair(1,"boost::assign"); BOOST_ASSERT(v.size()==10); BOOST_ASSERT(l.size()==6); BOOST_ASSERT(s.size()==6); }如上我们可以很容易通过x+=arg1,arg2,arg3,....argN;的方式对一个标准容器赋值
2.使用boost::assign对标准容器初始化
使用boost::assign初始化主要依靠list_of(), map_list_of(), tuple_list_of() 这三个函数,使用方式如下:
std::list<int> l=list_of(5)(9)(3)(7)(9649); std::vector<int> v=ref_list_of(6)(7)(416);//ref_list_of参数可以传入引用 std::map<int,std::string> mp=map_list_of(1,"first")(2,"second"); // 二维数组 std::vector<std::vector<int>> vp = list_of(list_of(1)(2)) (list_of(3)(4)); vp += list_of(5)(6), list_of(7)(8);
这里借用一段代码:
/ 减少重复输入: // assign库提供repeat(),repeat_fun()和range()三个函数来减少重复的输入 void test_assign_repeat() { using namespace boost::assign; std::vector<int> v = list_of(1).repeat(3, 2)(3)(4)(5); // 1, 2, 2, 2, 3, 4, 5 std::copy(v.cbegin(), v.cend(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; std::deque<int> d; push_front(d).range(v.begin(), v.begin() + 5); // 3, 2, 2, 2, 1 std::copy(d.cbegin(), d.cend(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; }
上面代码演示了repeat()等的用法,他用来重复输入
3.使用insert()等函数进行插入
这个我没有使用过,因为上面的足矣应对大部分情况了
#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 ); BOOST_ASSERT( months.size() == 12 ); BOOST_ASSERT( months["january"] == 31 ); }很容易看得出这其实就是改版list _of()