1 /* Copyright 2016-2017 Joaquin M Lopez Munoz.
2 * Distributed under the Boost Software License, Version 1.0.
3 * (See accompanying file LICENSE_1_0.txt or copy at
4 * http://www.boost.org/LICENSE_1_0.txt)
5 *
6 * See http://www.boost.org/libs/poly_collection for library home page.
7 */
8
9 /* examples of insertion and emplacement */
10
11 #include <algorithm>
12 #include <array>
13 #include <boost/poly_collection/base_collection.hpp>
14 #include <random>
15 #include "rolegame.hpp"
16
main()17 int main()
18 {
19 boost::base_collection<sprite> c;
20
21 // populate c
22
23 std::mt19937 gen{92748}; // some arbitrary random seed
24 std::discrete_distribution<> rnd{{1,1,1}};
25 for(int i=0;i<8;++i){ // assign each type with 1/3 probability
26 switch(rnd(gen)){
27 case 0: c.insert(warrior{i});break;
28 case 1: c.insert(juggernaut{i});break;
29 case 2: c.insert(goblin{i});break;
30 }
31 }
32
33 auto render=[](const boost::base_collection<sprite>& c){
34 const char* comma="";
35 for(const sprite& s:c){
36 std::cout<<comma;
37 s.render(std::cout);
38 comma=",";
39 }
40 std::cout<<"\n";
41 };
42 render(c);
43
44 //[insertion_emplacement_1]
45 c.insert(c.begin(),juggernaut{8});
46 //]
47 render(c);
48
49 //[insertion_emplacement_2]
50 c.insert(c.begin(),goblin{9});
51 //]
52 render(c);
53
54 //[insertion_emplacement_3]
55 c.insert(c.begin<juggernaut>()+2,juggernaut{10});
56 // ^^ remember local iterators are random access
57 //]
58 render(c);
59
60 //[insertion_emplacement_4]
61 //= c.insert(c.begin(typeid(warrior)),juggernaut{11}); // undefined behavior!!
62 //]
63
64 //[insertion_emplacement_5]
65 boost::base_collection<sprite> c2;
66
67 c2.insert(c.begin(),c.end()); // read below
68 //<-
69 render(c2);
70 //->
71
72 // add some more warriors
73 std::array<warrior,3> aw={{11,12,13}};
74 c2.insert(aw.begin(),aw.end());
75 //<-
76 render(c2);
77 //->
78
79 // add some goblins at the beginning of their segment
80 std::array<goblin,3> ag={{14,15,16}};
81 c2.insert(c2.begin<goblin>(),ag.begin(),ag.end());
82 //<-
83 render(c2);
84 //->
85 //]
86
87 //[insertion_emplacement_6]
88 //<-
89 // same as line at beginning of previous snippet
90 //->
91 c2.insert(c.begin(),c.end());
92 //]
93
94 //[insertion_emplacement_7]
95 //= c.emplace(11); // does not compile
96 //]
97
98 //[insertion_emplacement_8]
99 c.emplace<goblin>(11); // now it works
100 //]
101 render(c);
102
103 //[insertion_emplacement_9]
104 c.emplace_hint<juggernaut>(c.begin(),12); // at the beginning if possible
105 c.emplace_pos<goblin>(c.begin<goblin>()+2,13); // amidst the goblins
106 c.emplace_pos<warrior>(c.begin(typeid(warrior)),14); // local_base_iterator
107 //]
108 render(c);
109 }
110