-->

C++ - Vectors Part 2: Modifying Vectors

Vectors offer methods to add, remove, and modify elements dynamically.

Examples and Explanation

Adding Elements

vec.push_back(10);

vec.emplace_back(20); // More efficient than push_back

Explanation: push_back() and emplace_back() add elements to the end of the vector. emplace_back() is faster as it constructs the element in place.

Inserting Elements

vec.insert(vec.begin() + 1, 15); // Insert 15 at the second position

Explanation: The insert() method allows adding elements at specific positions.

Removing Elements

vec.pop_back(); // Remove the last element

vec.erase(vec.begin() + 1); // Remove the second element

Explanation: Use pop_back() to remove the last element and erase() to remove elements from specific positions.

Clearing a Vector

vec.clear();

Explanation: The clear() method empties the vector, making its size zero.