Previous Table of Contents Next


7.1.2. Elementary C++ Examples

The classic example of a small C++ program announces its presence and then exits:

   /* A small C++ program */

   #include <iostream>
   using namespace std;     // Access the standard library
   int main()
   {
       cout << “Hello, world!” << endl;
       return 0;
   }

This program begins with a comment. Comments in C++ programs either begin with /* and end with the next */, or begin with // and end at the end of the line. Comments do not nest.

The next line of this program tells the compiler to use the standard I/O library. We can think of it as a request to copy the contents of a file that contains appropriate declarations into the program in place of the #include directive itself. The third line departs slightly from pedantically recommended practice and tells the compiler to make all the names from the standard library available to the program without further formality. Without that third line, the references to cout and endl would need to be spelled std::cout and std::endl.

On the next line begins the definition of a function called main, which returns a value of type int. Then comes a request to print on the file cout (which represents the standard output stream for the program) the string Hello, world!, followed by a special value endl called a manipulator.

This manipulator does two things: It causes the output stream to begin a new line, and it also forces out any characters that might have been buffered as a result of previous output. Finally, the program returns a value of 0 to the operating system, which value represents successful completion.

The reason that we can use << to print on cout is that cout has an appropriately defined type. Part of that definition says that when the << operator uses objects of that type as its left argument, the effect is to write a representation of the operator’s right argument into the output stream that the left argument denotes. Thus, for example, we can print the value of √2 by writing

   #include <iostream>
   #include <math>
   using namespace std;

   int main()
   {
       cout << “The square root of 2 is “ << sqrt(2.0) << endl;
       return 0;
   }

This program prints values of three different types: a string literal, a real number, and a manipulator. We shall see later how the C++ language facilities make it possible for the library to contain enough information to let the compiler decide, with no execution-time overhead at all, which library services are appropriate for printing each of these values.

As a more abstract example, here is a program that reads its standard input and counts how many times each distinct word appears in that input:

   #include <iostream>
   #include <iomanip>
   #include <map>
   #include <string>
   using namespace std;

   int main()
   {
       string s;
       map<string, int> m;

       while (cin >> s)
             ++m[s];
       map<string, int>::const_iterator it;
       for (it = m.begin(); it != m.end(); ++it)
             cout << setw(8) << it->second << “ “ << it->first << endl;

       return 0;
   }

The four #include directives tell the compiler about our intent to use various library facilities: <iostream> gives us cin, cout, and the associated << and >> operators; <iomanip> gives us the setw manipulator; and <string> and <map> give us the types with those names. As before, using namespace std; makes it unnecessary to identify the individual names that we use from the standard library.

This program uses a library data structure called a map, which is also sometimes called an associative array. It may be useful to think of it as a kind of array whose “subscripts” are not necessarily integers. In this particular example, those subscripts are strings and the array elements themselves are integers.

The first thing the program does is to read its entire input and use an associative array to count words:

   while (cin >> s)
         ++m[s];

This piece of code crams a lot into its two lines.

The expression cin >> s is a request to read from the standard input (identified by the library object cin) into a local variable, of type string, named s. In addition to reading from its input file, the >> operator returns a value that indicates whether the input attempt was successful. The while loop therefore executes its subject statement ++m[s] repeatedly, as long as there is input to be read.

The statement

   ++m[s];

is essentially equivalent to

   m[s] = m[s] + 1;

so it adds 1 to the value of m[s]. Here, we can think of m[s] as being the element of m that has index s, but with the added—and essential—wrinkle that if such an element does not already exist, it will be created, with value 0, immediately before we try to increment it. All this behavior is defined as part of the map type.

The other knowledge we need in order to understand this fragment is that the string type represents a variable-length character string, and that the normal behavior of the >> operator when presented with a string is to read the next word from the input and store the value of that word in the string.

In short, because of the abstractions provided by the cin object and the string and map types from the standard library, our two-line loop does a lot of useful work.


Previous Table of Contents Next