Vector
-
In C++, the Standard Template Library (STL) provides a vector container that is a dynamic array-like data structure. It is part of the C++ Standard Library and is a very versatile and commonly used data structure for storing and managing collections of objects. Here's how you can work with vectors in C++
-
You need to include the
header to use vectors. Here's how you can do it
#include < Vector>
-
1) Creates an empty vector of integers
vector< int> myVector;
2) Creates a vector of doubles and initializes it with values
vector< double> doubleVector = {1.2, 3.4, 5.6}; -
You can add elements to a vector using the push_back() method:
myVector.push_back(42);
myVector.push_back(15); -
You can access elements using the [] operator or the at() method:
int value1 = myVector[0];
int value2 = myVector.at(1); -
There are various methods to iterate through a vector by simple
1)for
2)while
Using Simple For loop
for (int i = 0; i < myVector.size(); i++)
{
Access elements using myVector[i]
}
Using For each loop
for(auto it : myvector)
{
it
}
-
You can get the size (number of elements) of a vector using the size() method
int size = myVector.size(); -
You can remove elements using the pop_back() method to remove the last element or use the erase() method to remove elements at specific positions
1) Removes the last element
myVector.pop_back();
2)Removes the element at index 2
myVector.erase(myVector.begin() + 2);