1 // test/demo of generic lists
5 #define tassert(ex) {if ((ex)) cerr << #ex << "\n"; \
6 else _assert(#ex, __FILE__,__LINE__); }
12 bool int_compare(int a
, int b
)
22 void print(list
<int>& l
)
24 for (list
<int>::iterator it
= l
.begin(); it
!= l
.end(); it
++)
39 void sequence(list
<int>& a
, int lo
, int hi
)
41 back_insert_iterator
<list
<int> > it(a
);
50 old_rand
= ((long)old_rand
* (long)1243) % (long)971;
54 void randseq(list
<int>& a
, int n
)
56 back_insert_iterator
<list
<int> > it(a
);
58 *it
++ = get_rand() % 50;
61 int array1
[] = { 9, 16, 36 };
62 int array2
[] = { 1, 4 };
66 list
<int> l1 (array1
, array1
+ 3);
67 list
<int> l2 (array2
, array2
+ 2);
68 list
<int>::iterator i1
= l1
.begin ();
70 list
<int>::iterator i2
= l1
.begin ();
71 while (i2
!= l1
.end ())
72 cout
<< *i2
++ << endl
;
79 list
<int>::iterator it
, bit
;
81 cout
<< "\nlist<int> a = sequence(1, 20);\n"; print(a
);
82 for (it
= a
.begin (), i
= 0; it
!= a
.end (); it
++, i
++)
83 assert (*it
== i
+ 1);
86 cout
<< "\nlist<int> b = randseq(20);\n"; print(b
);
88 c
.insert (c
.end(), a
.begin(), a
.end());
89 c
.insert (c
.end(), b
.begin(), b
.end());
90 cout
<< "\nlist<int> c = a and b;\n"; print(c
);
93 for (it
= a
.begin(); it
!= a
.end(); it
++)
94 d
.insert(d
.end (), inc(*it
));
95 cout
<< "\nlist<int> d = map(inc, a);\n"; print(d
);
98 back_insert_iterator
<list
<int> > e_insertor (e
);
99 reverse_copy (a
.begin(), a
.end (), e_insertor
);
100 cout
<< "\nlist<int> e = reverse(a);\n"; print(e
);
103 for (it
= a
.begin(); it
!= a
.end(); it
++)
105 f
.insert(f
.end (), *it
);
106 cout
<< "\nlist<int> f = select(is_odd, a);\n"; print(f
);
108 for (it
= f
.begin(); it
!= f
.end(); it
++)
110 ff
.insert(ff
.end (), *it
);
114 for (it
= a
.begin(); it
!= a
.end(); it
++)
116 cout
<< "\nint red = a.reduce(plus, 0);\n"; cout
<< red
;
117 it
= a
.begin(); ++it
; ++it
;
119 cout
<< "\nint second = a[2];\n"; cout
<< second
;
121 for (it
= a
.begin(), bit
= b
.begin(); it
!= a
.end () && bit
!= b
.end (); )
122 g
.insert (g
.end (), *it
++ + *bit
++);
123 cout
<< "\nlist<int> g = combine(plus, a, b);\n"; print(g
);
124 g
.remove_if (is_odd
);
125 cout
<< "\ng.del(is_odd);\n"; print(g
);
127 ff
.erase (ff
.begin (), ff
.end());
128 for (it
= g
.begin(); it
!= g
.end(); it
++)
130 ff
.insert (ff
.end (), *it
);
134 for (it
= b
.begin(); bit
= it
++, it
!= b
.end (); ) assert (*it
>= *bit
);
135 cout
<< "\nb.sort(int_compare);\n"; print(b
);
138 back_insert_iterator
<list
<int> > h_insertor (h
);
139 merge (a
.begin (), a
.end (), b
.begin (), b
.end (), h_insertor
, int_compare
);
140 cout
<< "\nlist<int> h = merge(a, b, int_compare);\n"; print(h
);
141 for (it
= h
.begin(); bit
= it
++, it
!= h
.end (); ) assert (*it
>= *bit
);
143 cout
<< "\nh via iterator:\n";
144 for (it
= h
.begin(); it
!= h
.end (); it
++)