Previous chapter: Chapter 5: Functions: Modularizing C++ Code
Data structures are how programmers organize information efficiently. This chapter introduces arrays for storing collections of the same type and the essential std::string class for robust text handling in C++.
1. Arrays: Storing Homogeneous Collections
An array is a data structure for storing a fixed-size, sequential collection of elements of the same data type.
Declaring and Initializing Arrays
You declare an array by specifying the type, a name, and the number of elements in square brackets [].
// Declaring an array of 5 integers
int scores[5];
// Declaring and initializing with a list
int grades[3] = {85, 92, 78};
// Allowing the compiler to determine the size
int numbers[] = {10, 20, 30, 40}; // Size is implicitly 4
Accessing Array Elements
Array elements are accessed using a zero-based index. The first element is at index 0, and the last is at index $N-1$ (where $N$ is the size).
int grades[3] = {85, 92, 78};
// Accessing:
std::cout << "First grade: " << grades[0] << std::endl; // Output: 85
// Modifying:
grades[2] = 80;
std::cout << "New third grade: " << grades[2] << std::endl; // Output: 80
Iterating Over Arrays
The for loop (introduced in Chapter 4) is the perfect tool for processing every element in an array.
int ages[] = {25, 30, 18, 45};
int size = 4;
for (int i = 0; i < size; i++) {
std::cout << "Age at index " << i << ": " << ages[i] << std::endl;
}
2. The Modern C++ String Class (std::string)
While the basic char type can hold a single character, C++ uses the std::string class (part of the Standard Library) to handle sequences of characters (text). Using std::string is highly recommended over the older, more complex C-style character arrays.
To use std::string, you must include the <string> header.
#include <string>
#include <iostream>
int main() {
std::string first_name = "Jane";
std::string last_name("Doe");
std::string full_name = first_name + " " + last_name; // Concatenation
std::cout << "Full name: " << full_name << std::endl;
// Output: Full name: Jane Doe
return 0;
}
Key std::string Operations
| Operation | Description | Example |
|---|
| + or += | Concatenation | s1 = s2 + s3; |
| .length() or .size() | Gets the number of characters | full_name.length() |
| [index] | Accesses a character | first_name[0] (returns 'J') |
| .append() | Adds characters to the end | s1.append(" Smith"); |
3. Multidimensional Arrays
Multidimensional arrays are arrays of arrays. The most common is a 2D array, which is useful for representing grids, matrices, or tables.
// Declares a 3x3 matrix (3 rows, 3 columns)
int matrix[3][3] = {
{1, 2, 3}, // Row 0
{4, 5, 6}, // Row 1
{7, 8, 9} // Row 2
};
// Accessing the element in Row 1, Column 0 (the value 4)
std::cout << matrix[1][0] << std::endl;