Arrays and Vectors in C++ - An Introduction
Arrays and vectors are fundamental data structures in C++ for storing collections of values. They are used to manage and manipulate data efficiently. In this guide, we'll explore the basics of arrays and vectors in C++.
Arrays
An array is a fixed-size collection of elements of the same data type. Elements are accessed by their index, which starts at 0. Here's how to declare and use arrays:
#include <iostream>
using namespace std;
int main() {
int numbers[5]; // Declare an integer array with 5 elements
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
cout << "Element at index 2: " << numbers[2] << endl;
return 0;
}
In this example, we declare an integer array with five elements and access the elements using their indices.
Vectors
A vector is a dynamic array provided by the Standard Template Library (STL). Vectors can grow or shrink in size as needed. Here's how to declare and use vectors:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers; // Declare a vector of integers
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);
numbers.push_back(40);
numbers.push_back(50);
cout << "Element at index 2: " << numbers[2] << endl;
return 0;
}
In this example, we declare a vector of integers and use the push_back
method to add elements. Vectors automatically manage their size.
Arrays vs. Vectors
Arrays have a fixed size determined at compile-time, while vectors can grow or shrink as needed at runtime. Vectors provide more flexibility, but arrays are useful when a fixed-size collection is required.
Common Operations
Both arrays and vectors support common operations like accessing elements, changing values, and iterating through the elements using loops.
// Accessing elements
int element = numbers[2];
// Changing values
numbers[3] = 42;
// Iterating through elements
for (int i = 0; i < numbers.size(); i++) {
cout << numbers[i] << " ";
}
Conclusion
Arrays and vectors are foundational data structures in C++ that allow you to store and manipulate collections of data. As you continue your C++ journey, you'll explore more advanced operations and use cases for these data structures.