Ne.app NeANT
The Ne.app NeANT User module of the NeANT distribution.
list.cpp
Go to the documentation of this file.
1
29#include <algorithm> // for find
30#include <list> // for list
31#include <string> // for string
32#include <iostream> // for cout
33
34#include <examples.h>
35
36
37typedef std::list<std::string, std::allocator<std::string> > StringList;
38
39
40// stream out a list of strings
41std::ostream& operator<< (std::ostream &out, const StringList &l)
42{
43 // create a sentry object to guard the stream
44 const std::ostream::sentry guard (out);
45
46 if (guard) {
47
48 // the guard succeeded in preparing the stream for output
49
50 for (StringList::const_iterator i = l.begin (); i != l.end (); ++i) {
51
52 // insert the string into the stream object's buffer
53 const std::streamsize n =
54 out.rdbuf ()->sputn ((*i).data (), (*i).size ());
55
56 // insert the space character into the buffer
57 if ( std::streamsize ((*i).size ()) != n
58 || std::ostream::traits_type::to_int_type (' ')
59 != out.rdbuf ()->sputc (' ')) {
60
61 // set badbit if either operation failed
62 out.setstate (std::ios::badbit);
63 break;
64 }
65 }
66 }
67
68 return out;
69}
70
71
72int main ()
73{
74 // Create a list of critters.
75 StringList critters;
76
77 // Insert a few critters.
78 critters.insert (critters.begin (), "antelope");
79 critters.insert (critters.begin (), "bear");
80 critters.insert (critters.begin (), "cat");
81
82 // Print out the list.
83 std::cout << critters << '\n';
84
85 // Change cat to cougar.
86 *std::find (critters.begin (),critters.end (), "cat") = "cougar";
87 std::cout << critters << '\n';
88
89 // Put a zebra at the beginning, an ocelot ahead of antelope,
90 // and a rat at the end.
91 critters.push_front ("zebra");
92 critters.insert (std::find (critters.begin (), critters.end (),
93 "antelope"), "ocelot");
94 critters.push_back ("rat");
95 std::cout << critters << '\n';
96
97 // Sort the list (Use list's sort function since the
98 // generic algorithm requires a random access iterator
99 // and list only provides bidirectional)
100 critters.sort ();
101 std::cout << critters << '\n';
102
103 // Now let's erase half of the critters.
104 StringList::size_type half = critters.size () / 2;
105 for (StringList::size_type i = 0; i != half; ++i)
106 critters.erase (critters.begin ());
107
108 std::cout << critters << '\n';
109
110 return 0;
111}
#define i
Definition 17.names.cpp:126
#define n
Definition 17.names.cpp:130
const int out
std::list< std::string, std::allocator< std::string > > StringList
Definition list.cpp:37
int main()
Definition list.cpp:72
std::ostream & operator<<(std::ostream &out, const StringList &l)
Definition list.cpp:41