4.4.3 初始化容器元素
操作符+=和()解决了对容器的赋值问题,但有的时候我们需要在容器构造的时候就完成数据的填充,这种方式较赋值更为高效。C++(www.cppentry.com)内建的数组和标准字符串类string支持这样做,但其他STL容器则不行。
assign库使用list_of()、map_list_of()/pair_list_of()和tuple_list_of()三个函数解决了这个问题。
list_of
list_of()函数的用法与之前的insert()、push_back()等函数很相似,也重载了括号、逗号操作符。它很智能,返回一个匿名的列表,可以赋值给任意容器。
演示list_of用法的代码如下:
- #include <boost/assign.hpp>
- int main()
- {
- using namespace boost::assign;
-
- vector<int> v = list_of(1)(2)(3)(4)(5);
- // v = [1, 2, 3, 4, 5]
-
- deque<string> d =
- (list_of("power")("bomb"),"phazon","suit"); //注意括号的使用
- // d = [power bomb phazon suit]
-
- set<int> s = (list_of(10), 20,30,40,50); //注意括号的使用
- // s = {10 20 30 40 50}
-
- map<int, string> m = list_of(make_pair(1, "one"))(make_pair(2, "two"));
- // m = [(1, “one”) (2, “two”)]
- }
list_of()函数可以全部使用括号操作符,也可以把括号与逗号结合起来,但使用后者时需要将整个list_of表达式用括号括起来,否则会使编译器无法推导出list_of的类型而无法赋值。
map_list_of/pair_list_of
使用list_of()处理map容器不是很方便,于是map_list_of()/pair_list_of()应运而生,map_list_of()可以接受两个参数,然后自动构造std::pair对象插入map容器,pair_list_of()则纯粹是map_list_of的同义词,两者的用法功能完全相同。
map_list_of()和pair_list_of()的基本形式如下:
- template< class Key, class T >
- map_list_of( const Key& k, const T& t ); //key,value
-
- template< class F, class S >
- pair_list_of( const F& f, const S& s ) //first,second
- {
- return map_list_of( f, s );
- }
演示map_list_of用法的代码如下:- #include <boost/assign.hpp>
- int main()
- {
- using namespace boost::assign;
-
- map<int, int> m1 = map_list_of(1, 2)(3, 4)(5, 6);
- //m1 = [(1, 2)(3, 4)(5, 6)]
-
- map<int, string> m2 = map_list_of(1, "one")(2, "two");
- //m2 = [(1, "one")(2, "two")]
- }
tuple_list_of
tuple_list_of用于初始化元素类型为tuple的容器,tuple是Boost引入的一种新的容器/数据结构,关于tuple和的tuple_list_of的用法请参见7.6.8节(第282页)。