4.4.5 与非标准容器工作
assign库不仅支持全部八个STL标准容器(vector、string、deque、list、set、multiset、map、multimap),也对STL中的容器适配器提供了适当的支持,包括stack、queue和priority_queue。
因为stack等容器适配器不符合容器的定义,没有insert、push_back等成员函数,所以不能使用赋值的方式填入元素,只能使用初始化的方式,并在list_of表达式最后使用to_adapter()成员函数来适配到非标准容器。如果使用逗号操作符还需要把整个表达式用括号括起来,才能使用点号调用to_adapter()。
示范assign库应用于容器适配器的代码如下:
- #include <boost/assign.hpp>
- #include <stack>
- #include <queue>
-
- int main()
- {
- using namespace boost::assign;
-
- stack<int> stk = (list_of(1), 2, 3).to_adapter();
- while(!stk.empty()) //输出stack的内容
- {
- cout << stk.top() << " ";
- stk.pop();
- }
- cout << endl;
-
- queue<string> q = (list_of("china")("us")("uk")).repeat(2, "russia").to_ adapter();
- while(!q.empty()) //输出queue的内容
- {
- cout << q.front() << " ";
- q.pop();
- }
- cout << endl;
-
- priority_queue<double> pq = (list_of(1.414), 1.732, 2.236).to_adapter();
- while(!pq.empty()) //输出优先队列的内容
- {
- cout << pq.top() << " " ;
- pq.pop();
- }
-
- }
程序运行结果如下:- 3 2 1
- china us uk russia russia
- 2.236 1.732 1.414
assign库也支持部分不在STL中定义的非标准容器,如STLport中的slist和hash_ set/hash_map,因为它们符合容器的定义,故用法与标准容器没有什么区别。
示范assign库应用于非标准容器的代码如下:
- #include <boost/assign.hpp>
- #include <hash_map> //非标准的散列映射容器
- #include <slist> //非标准的单向链表
- int main()
- {
- using namespace boost::assign;
-
- slist<int> sl;
- push_front(sl), 1,2,3,4,5; //不能用push_back和insert
-
- hash_map<string, int> hm = map_list_of("one", 1)("two", 2);
- }
此外,assign库还支持大部分Boost库容器,如array、circular_buffer、unordered等,用法同样与标准容器基本类似,在第7章可以找到更多的示例代码。