stl vector

The std::vector is a container in the C++ Standard Library that provides dynamic array-like functionality. It allows for the storage and manipulation of a sequence of elements, which can be of any type.

To use the std::vector in your C++ code, you need to include the header file:

include

Once you have included the header file, you can declare a vector using the following syntax:

std::vector vectorName;

Here, T represents the type of elements that the vector will store. For example, if you want to create a vector of integers, you would use:

std::vector myVector;

To add elements to the vector, you can use the push_back() function. This function appends the specified element to the end of the vector:

myVector.push_back(10); // Adds the integer 10 to the end of the vector

You can access the elements of the vector using the [] operator. The index starts from 0, so the first element is at index 0:

int firstElement = myVector[0]; // Retrieves the first element of the vector

To get the size of the vector, you can use the size() function:

int vectorSize = myVector.size(); // Retrieves the number of elements in the vector

To iterate over the elements of the vector, you can use a for loop:

for (int i = 0; i < myVector.size(); i++) { int element = myVector[i]; // Do something with the element }

You can also use the range-based for loop introduced in C++11:

for (int element : myVector) { // Do something with the element }

To remove elements from the vector, you can use the erase() function. This function takes an iterator as a parameter and removes the element at that position:

auto it = myVector.begin(); // Iterator pointing to the first element myVector.erase(it); // Removes the first element from the vector

You can also clear the entire vector using the clear() function:

myVector.clear(); // Removes all elements from the vector

These are some of the basic operations that you can perform with the std::vector in C++. The vector class provides many other useful functions and methods, such as insert(), resize(), and swap(), which you can explore in the C++ documentation.