Arrays, Vectors, and Strings in C++
C++ provides powerful data structures like arrays, vectors, and strings to manage
collections of data. Each has unique features and use cases, making them
essential tools in C++ programming.
1. Arrays
An array is a fixed-size collection of elements of the same data type, stored
contiguously in memory.
1.1 Declaration and Initialization
Syntax:
data_type array_name[size];
Examples:
int numbers[5]; // Declaration
int scores[5] = {10, 20, 30, 40, 50}; // Initialization
1.2 Accessing Elements
Array elements are accessed using indices, starting from 0.
Example:
cout << scores[2]; // Output: 30
scores[3] = 45; // Modifies the fourth element
1.3 Multidimensional Arrays
C++ supports multidimensional arrays like 2D arrays.
, Example:
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
cout << matrix[1][2]; // Output: 6
2. Vectors
Vectors are dynamic arrays provided by the C++ Standard Template Library (STL).
They can resize automatically when elements are added or removed.
2.1 Declaration and Initialization
Syntax:
#include <vector>
std::vector<data_type> vector_name;
Example:
std::vector<int> numbers = {1, 2, 3, 4};
2.2 Common Operations
Adding Elements: push_back()
Removing Elements: pop_back()
Accessing Elements: at() or []
Getting Size: size()
Example:
std::vector<int> nums;
nums.push_back(10); // Adds 10
nums.push_back(20); // Adds 20
cout << nums.at(1); // Output: 20
nums.pop_back(); // Removes last element
C++ provides powerful data structures like arrays, vectors, and strings to manage
collections of data. Each has unique features and use cases, making them
essential tools in C++ programming.
1. Arrays
An array is a fixed-size collection of elements of the same data type, stored
contiguously in memory.
1.1 Declaration and Initialization
Syntax:
data_type array_name[size];
Examples:
int numbers[5]; // Declaration
int scores[5] = {10, 20, 30, 40, 50}; // Initialization
1.2 Accessing Elements
Array elements are accessed using indices, starting from 0.
Example:
cout << scores[2]; // Output: 30
scores[3] = 45; // Modifies the fourth element
1.3 Multidimensional Arrays
C++ supports multidimensional arrays like 2D arrays.
, Example:
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
cout << matrix[1][2]; // Output: 6
2. Vectors
Vectors are dynamic arrays provided by the C++ Standard Template Library (STL).
They can resize automatically when elements are added or removed.
2.1 Declaration and Initialization
Syntax:
#include <vector>
std::vector<data_type> vector_name;
Example:
std::vector<int> numbers = {1, 2, 3, 4};
2.2 Common Operations
Adding Elements: push_back()
Removing Elements: pop_back()
Accessing Elements: at() or []
Getting Size: size()
Example:
std::vector<int> nums;
nums.push_back(10); // Adds 10
nums.push_back(20); // Adds 20
cout << nums.at(1); // Output: 20
nums.pop_back(); // Removes last element