Mark As Completed Discussion

Vector

In the world of programming, a vector is a dynamic array that can grow or shrink in size at runtime. It is one of the most commonly used data structures in C++ and provides several important features.

The vector in C++ is defined in the <vector> header and is part of the Standard Template Library (STL). It is implemented as a template class, allowing us to create vectors of different types, such as int, double, or even custom classes.

Creating a Vector

To create a vector, we need to include the <vector> header and declare a vector object with the desired type, followed by the name.

Here's an example of creating a vector of integers:

TEXT/X-C++SRC
1#include <iostream>
2#include <vector>
3
4int main() {
5  // Declare a vector of integers
6  std::vector<int> numbers;
7
8  // ...
9}

Adding Elements to a Vector

We can add elements to a vector using the push_back() function, which adds the element to the end of the vector. The vector automatically grows in size as we add elements.

Here's an example of adding elements to a vector:

TEXT/X-C++SRC
1// Add elements to the vector
2numbers.push_back(10);
3numbers.push_back(20);
4numbers.push_back(30);
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment