Cover Image for C++ Vector
121 views

C++ Vector

The vector is a dynamic array-like container provided by the C++ Standard Library (part of the Standard Template Library, or STL). Vectors are similar to arrays but offer dynamic sizing, automatic memory management, and a range of convenient methods for manipulating data.

Here’s how to work with vectors in C++:

1. Include the necessary header:

C++
#include <vector>

2. Declare a vector:

C++
std::vector<T> myVector;
  • Replace T with the data type of the elements you want to store in the vector.

3. Add elements to the vector:

You can add elements to a vector using various methods:

  • push_back(): Adds an element to the end of the vector.
C++
myVector.push_back(42);
  • emplace_back(): Constructs an element in place at the end of the vector (allows you to avoid unnecessary copies or moves).
C++
myVector.emplace_back(42);

4. Access elements:

You can access vector elements using indexing (like arrays) or using iterators:

  • Using indexing:
C++
int element = myVector[0];
  • Using iterators (preferred when iterating through the vector):
C++
for (auto it = myVector.begin(); it != myVector.end(); ++it) {
    int element = *it;
}

5. Size and capacity:

  • size(): Returns the number of elements in the vector.
C++
int size = myVector.size();
  • capacity(): Returns the current storage capacity of the vector (how many elements it can hold before resizing).
C++
int capacity = myVector.capacity();

6. Remove elements:

You can remove elements from the vector using methods like pop_back() or erase().

  • pop_back(): Removes the last element from the vector.
C++
myVector.pop_back();
  • erase(): Removes one or more elements by specifying an iterator or a range.
C++
myVector.erase(myVector.begin() + 2); // Removes the third element

7. Clear the vector:

You can remove all elements from the vector using the clear() method:

C++
myVector.clear();

8. Vector initialization:

You can initialize vectors with values using various constructors:

C++
std::vector<int> numbers = {1, 2, 3, 4, 5};

9. Other operations:

Vectors support a wide range of operations, including sorting, searching, and more. You can use standard algorithms from the C++ Standard Library with vectors.

C++
#include <algorithm>

// Sort the vector in ascending order
std::sort(myVector.begin(), myVector.end());

Vectors in C++ provide a flexible and convenient way to manage collections of data. They automatically handle memory allocation and resizing, making them a popular choice for dynamic arrays in C++ programs.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS