Polonius: What do you read my lord?
Hamlet: Words, words, words.
WILLIAM SHAKESPEARE, Hamlet
This chapter discusses two topics that use arrays or are related to arrays: strings and vectors. Although strings and vectors are very closely related, this relationship is not always obvious, and no one of these topics depends on the other. The topics of strings and vectors can be covered in either order.
Sections 8.1 and 8.2 present two types whose values represent strings of characters, such as "Hello"
. One type, discussed in Section 8.1, is just an array with base type char
that stores strings of characters in the array and marks the end of the string with the null character '\0'
. This is the older way of representing strings, which C++ inherited from the C programming language. These sorts of strings are called C strings. Although C strings are an older way of representing strings, it is difficult to do any sort of string processing in C++ without at least passing contact with C strings. For example, quoted strings, such as "Hello"
, are implemented as C strings in C++.
The ANSI/ISO C++ standard includes a more modern string-handling facility in the form of the class string
. The class string
is the second string type that we will discuss in this chapter and is covered in Section 8.2.
Vectors can be thought of as arrays that can grow (and shrink) in length while your program is running. In C++, once your program creates an array, it cannot change the length of the array. Vectors serve the same purpose as arrays except that they can change length while the program is running.
Sections 8.1 and 8.2, which cover strings, and Section 8.3 which covers vectors, are independent of each other. If you wish to cover vectors before strings, that is fine.
Section 8.1 on C strings uses material from Chapters 2 through 6, and Sections 7.1, 7.2, and 7.3 of Chapter 7. Section 8.2 on the string class uses Section 8.1 and material from Chapters 2 through 6 and Sections 7.1, 7.2, and 7.3 of Chapter 7. Section 8.3 on vectors uses material from Chapters 2 through 6 and Sections 7.1, 7.2, and 7.3 of Chapter 7.