To create a vector in C++, you need to include the <vector>
library.
#include <vector>
Once the library is included, you can declare a vector by specifying its type.
std::vector<int> myVector; // Creates an empty vector of integers
This creates an empty vector of integers named myVector
. You can also initialize the vector with initial values using initialization lists.
std::vector<int> myInitializedVector = {1, 2, 3, 4, 5}; // Initializes a vector with values
To add elements to the vector, you can use the push_back()
method.
myVector.push_back(10); // Adds the element 10 to the end of the vector
You can access elements of the vector using the subscript operator []
.
int firstElement = myVector[0]; // Retrieves the value at index 0
The size()
function returns the current size of the vector.
int vectorSize = myVector.size(); // Returns the number of elements in the vector
To iterate over the vector and perform operations on each element, you can use a for loop.
for (int i = 0; i < myVector.size(); i++) {
std::cout << myVector[i] << " "; // Prints each element followed by a space
}
Remember to include the <iostream>
library to use the std::cout
object for printing.
Vectors in C++ are versatile and provide many other useful functions like pop_back()
, insert()
, erase()
, and more. It is a powerful tool for dynamically managing collections of elements.
So, if you need to work with a dynamically resizable array in C++, a vector is a great choice to simplify your coding process and make your program more flexible and efficient.
#cplusplus #vector