Week 6: Working with Sequences - Arrays & Strings
Learn to store and manipulate ordered collections of data using arrays and strings in C++.
Explore Chapter 6Chapter 6: Arrays and Introduction to Strings
Arrays: Fixed-Size Sequences.
Arrays are fundamental data structures used to store a fixed-size, sequential collection of elements of the same data type. They provide contiguous memory allocation for their elements.
Declaration and Initialization
You declare an array by specifying the element type, the array name, and the size (number of elements) in square brackets `[]`.
int scores[5]; // Declares an array named 'scores' that can hold 5 integers
// Initialization at declaration
double temperatures[3] = { 98.6, 100.2, 99.1 }; // Using initializer list
char vowels[] = { 'a', 'e', 'i', 'o', 'u' }; // Size inferred from initializer list
If you provide an initializer list, you can optionally omit the size, and the compiler will determine it.
Accessing Elements (Indexing)
Array elements are accessed using zero-based indexing (the first element is at index 0) with square brackets.
#include <iostream>
int main() {
int numbers[4] = {10, 20, 30, 40};
std::cout << "First element: " << numbers[0] << std::endl; // Output: 10
std::cout << "Third element: " << numbers[2] << std::endl; // Output: 30
// Modifying an element
numbers[1] = 25;
std::cout << "Second element (modified): " << numbers[1] << std::endl; // Output: 25
// Important: C++ does NOT typically check array bounds!
// Accessing numbers[4] or numbers[-1] leads to UNDEFINED BEHAVIOR.
return 0;
}
Iterating Over Arrays
You can use loops (especially `for` loops) to process array elements.
double prices[] = {1.99, 5.50, 10.00, 0.75};
int numPrices = sizeof(prices) / sizeof(prices[0]); // Calculate array size
// Classic for loop
for (int i = 0; i < numPrices; ++i) {
std::cout << prices[i] << " ";
}
std::cout << std::endl;
// Range-based for loop (C++11 onwards)
for (double price : prices) {
std::cout << price << " ";
}
std::cout << std::endl;
Multidimensional Arrays (Basic).
C++ supports multidimensional arrays, which are essentially arrays of arrays. The most common is the 2D array, representing a grid or table.
Declaration and Initialization
// Declare a 2x3 integer array (2 rows, 3 columns)
int matrix[2][3];
// Declare and initialize
int grid[2][3] = {
{ 1, 2, 3 }, // Row 0
{ 4, 5, 6 } // Row 1
};
// Can omit the first dimension size if initializing
int grid2[][3] = { {1, 2, 3}, {4, 5, 6} };
Accessing Elements
Use two sets of square brackets: `arrayName[rowIndex][columnIndex]`.
std::cout << grid[0][1]; // Output: 2 (Element at row 0, column 1)
grid[1][2] = 55; // Modify element at row 1, column 2
Iterating
Nested loops are typically used to iterate over multidimensional arrays.
int rows = 2;
int cols = 3;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
std::cout << grid[i][j] << " ";
}
std::cout << std::endl;
}
C-style Strings (`char` arrays).
Before the introduction of the `std::string` class, C++ (inheriting from C) primarily handled strings as arrays of characters terminated by a special null character (`'\0'`).
Declaration and Initialization
char greeting[] = "Hello"; // Compiler adds null terminator '\0' automatically. Size is 6.
char message[20] = "World"; // Size 20, initialized with "World\0", rest are undefined/garbage.
char explicitNull[] = {'H', 'i', '\0'}; // Manually null-terminated.
Working with C-strings
Many C-style string manipulation functions are available in the `
#include <cstring>
#include <iostream>
int main() {
char str1[50] = "Hello";
char str2[] = ", World!";
std::strcat(str1, str2); // Concatenate str2 onto str1 (DANGEROUS if str1 isn't large enough!)
std::cout << str1 << std::endl; // Output: Hello, World!
std::cout << "Length: " << std::strlen(str1) << std::endl; // Output: Length: 13
return 0;
}
Caution: C-style strings are prone to errors, especially buffer overflows (writing past the end of the array), because they don't manage their own memory or track their size automatically. It's generally recommended to use `std::string` in modern C++.
Introduction to `std::string`.
The `std::string` class (from the `
Include Header
#include <string>
Creation and Initialization
std::string s1; // Empty string
std::string s2 = "Hello"; // Initialize with string literal
std::string s3("World"); // Initialize using constructor
std::string s4 = s2; // Copy initialization
Concatenation and Comparison
Operators work intuitively with `std::string`.
std::string combined = s2 + " " + s3 + "!"; // combined is "Hello World!"
if (s2 == "Hello") { // Comparison using ==
std::cout << "s2 is Hello" << std::endl;
}
Common Methods
`std::string` offers many useful member functions:
- `length()` or `size()`: Returns the number of characters.
- `empty()`: Returns `true` if the string is empty.
- `append()` or `+=`: Appends characters or another string.
- `find()`: Searches for a substring.
- `substr()`: Extracts a substring.
- `compare()`: Compares strings lexicographically.
- `[index]`: Access individual characters (like arrays, but safer with `at()` method).
std::string text = "Programming";
std::cout << "Length: " << text.length() << std::endl; // Output: 11
text += " is fun!"; // Append using +=
std::cout << text << std::endl; // Output: Programming is fun!
size_t pos = text.find("gram"); // Find substring
if (pos != std::string::npos) { // npos means 'not found'
std::cout << "'gram' found at index: " << pos << std::endl; // Output: 3
}
std::cout << "Character at index 1: " << text[1] << std::endl; // Output: r
`std::string` automatically handles memory management and prevents many errors common with C-style strings. Use it whenever possible in modern C++.