Vectors
Vectors are an important part of the C++ Standard Template Library (STL). They are similar to arrays, but with the added advantage of being dynamic in size. Unlike arrays, the size of vectors can be changed during runtime. In simple terms, a vector can be thought of as a container that can hold any type of data and provides the ability to resize itself automatically when an element is inserted or deleted.
Introduction to Vectors in C++
In C++, a vector is a dynamic array that grows and shrinks at runtime. It is an object-oriented and generic programming feature of the C++ programming language. A vector in C++ is a class in STL that represents an array. The main difference between a vector and an array is that the size of an array is fixed, while a vector's size can change dynamically, with its storage being handled automatically by the container.
Let's start with a simple example of how to declare a vector:
#include <vector>
int main() {
std::vector<int> myVector;
return 0;
}
In the above example, we have declared a vector named myVector
that can store integer values. We have not added any elements to it yet.
Adding Elements to a Vector
You can add elements to a vector using the push_back()
method. This method inserts an element at the end of the vector. Here's how you can do it:
#include <vector>
int main() {
std::vector<int> myVector;
for(int i = 0; i < 10; i++){
myVector.push_back(i);
}
return 0;
}
In this example, we have added the numbers from 0 to 9 to our vector using a for loop.
Accessing Elements in a Vector
You can access elements in a vector using the []
operator, similar to how you would with an array. Here's an example:
#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector;
for(int i = 0; i < 10; i++){
myVector.push_back(i);
}
std::cout << "The third element in the vector is: " << myVector[2] << std::endl;
return 0;
}
In this example, we have printed the third element in the vector, which is the number 2.
Modifying Elements in a Vector
You can modify an element in a vector using the []
operator. Here's an example:
#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector;
for(int i = 0; i < 10; i++){
myVector.push_back(i);
}
myVector[2] = 20;
std::cout << "The third element in the vector is now: " << myVector[2] << std::endl;
return 0;
}
In this example, we have changed the third element in the vector to 20.
Other Useful Methods
size()
: Returns the number of elements in the vector.empty()
: Returns whether the vector is empty.insert()
: Inserts new elements into the vector.pop_back()
: Removes the last element from the vector.clear()
: Removes all elements from the vector.
The vector is a very useful container in C++ as it provides dynamic sizes and a number of handy methods. With practice, you will find them to be an essential tool in your C++ programming toolkit.