Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Vector Operations in C++

C++ vector operations with STL algorithms: sort, reverse, find with distance, insert and erase at an index, and clear. Learn the cost of each one.

IntermediateSTL Containers ProgramsExample 2 of 10
vector-operations.cpp
1#include <iostream>
2#include <vector>
3#include <algorithm>
4using namespace std;
5
6int main() {
7 vector<int> vec = {5, 2, 8, 1, 9, 3};
8
9 cout << "Original vector: ";
10 for (int num : vec) {
11 cout << num << " ";
12 }
13 cout << endl;
14
15 // Sort vector
16 sort(vec.begin(), vec.end());
17 cout << "Sorted vector: ";
18 for (int num : vec) {
19 cout << num << " ";
20 }
21 cout << endl;
22
23 // Reverse vector
24 reverse(vec.begin(), vec.end());
25 cout << "Reversed vector: ";
26 for (int num : vec) {
27 cout << num << " ";
28 }
29 cout << endl;
30
31 // Find element
32 auto it = find(vec.begin(), vec.end(), 5);
33 if (it != vec.end()) {
34 cout << "Element 5 found at index: " << distance(vec.begin(), it) << endl;
35 }
36
37 // Insert element
38 vec.insert(vec.begin() + 2, 100);
39 cout << "\nAfter inserting 100 at index 2: ";
40 for (int num : vec) {
41 cout << num << " ";
42 }
43 cout << endl;
44
45 // Erase element
46 vec.erase(vec.begin() + 2);
47 cout << "After erasing element at index 2: ";
48 for (int num : vec) {
49 cout << num << " ";
50 }
51 cout << endl;
52
53 // Clear vector
54 vec.clear();
55 cout << "\nSize after clear: " << vec.size() << endl;
56 cout << "Is empty: " << (vec.empty() ? "Yes" : "No") << endl;
57
58 return 0;
59}

Sample Output

Element 5 found at index: 2

After the reverse, 5 is the third element.

After inserting 100 at index 2: 9 8 100 5 3 2 1

5 3 2 1 shifted right to make room.

In this one

  • How algorithms use begin() and end() iterators
  • How to sort and reverse a vector
  • How to check the result of find()
  • Why insert and erase in the middle cost O(n)

How it works

  1. 1

    Start with {5, 2, 8, 1, 9, 3}.

  2. 2

    sort → 1 2 3 5 8 9.

  3. 3

    reverse → 9 8 5 3 2 1.

  4. 4

    find 5 and print its index with distance → 2.

  5. 5

    insert 100 at index 2, then erase it.

  6. 6

    clear and check size and empty.

Edge cases

Value not found

Search for 42 instead of 5.

find returns vec.end(). The if check skips the print; dereferencing end() would be undefined.

Insert past the end

vec.insert(vec.begin() + 20, 1) on a 6-element vector.

The position must be between begin() and end(). Anything beyond is undefined behavior.

Iterators after insert

Keep the old it from find and use it after insert.

insert can reallocate, which invalidates every iterator into the vector. Search again after changing the vector.

What's going on

Once you have a vector, most real work is done with algorithms from <algorithm>. This program sorts, reverses, and searches a vector, then inserts and erases in the middle.

The algorithms take a pair of iterators instead of the vector itself. vec.begin() points at the first element and vec.end() points one past the last, so the pair covers the whole range.

sort(vec.begin(), vec.end()) arranges {5, 2, 8, 1, 9, 3} as 1 2 3 5 8 9. It runs in O(n log n).

reverse flips that to 9 8 5 3 2 1.

find(vec.begin(), vec.end(), 5) walks from the front and returns an iterator to the first 5, or vec.end() if there is none. That is why the code compares with vec.end() before using the result. distance(vec.begin(), it) turns the iterator into an index: 5 sits at index 2 in the reversed vector.

vec.insert(vec.begin() + 2, 100) puts 100 at index 2 and shifts everything after it one place right. vec.erase(vec.begin() + 2) removes it again and shifts the rest back. Both are O(n) because of that shifting, so a vector is a poor choice when you insert in the middle constantly.

clear() removes every element, so size() becomes 0 and empty() is true. The capacity usually stays the same, so the memory is kept for reuse.

The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <vector> is there because it provides vector container class. <algorithm> is there because it provides algorithms like sort(), reverse(), find(). Leave one out and the compiler stops at the first name it does not recognize.

Understanding Vector Operations

Operation Types:

Sorting: arrange elements in order
Reversing: reverse element order
Finding: locate specific element
Inserting: add element at position
Erasing: remove element at position
Clearing: remove all elements

Iterators:

begin(): points to first element
end(): points past last element
Used for range operations

Sorting Vector

Using sort():

sort(vec.begin(), vec.end());

What happens here:

Sorts elements in ascending order
Uses iterators to specify range
Modifies original vector
O(n log n) time complexity

Example:

{5, 2, 8, 1, 9, 3} → {1, 2, 3, 5, 8, 9}

Reversing Vector

Using reverse():

reverse(vec.begin(), vec.end());

What happens here:

Reverses order of elements
First becomes last, last becomes first
Uses iterators for range
O(n) time complexity

Example:

{1, 2, 3, 5, 8, 9} → {9, 8, 5, 3, 2, 1}

Finding Elements

Using find():

auto it = find(vec.begin(), vec.end(), 5);

What happens here:

Searches for value in range
Returns iterator to found element
Returns end() if not found
O(n) time complexity (linear search)

Checking Result:

if (it != vec.end()) {

// Element found

int index = distance(vec.begin(), it);

} else {

// Element not found

}

Inserting Elements

Using insert():

vec.insert(vec.begin() + 2, 100);

What happens here:

Inserts element at specified position
Shifts existing elements
Expensive for large vectors (O(n))
Position specified using iterator

Example:

Before: {9, 8, 5, 3, 2, 1}

After insert at index 2: {9, 8, 100, 5, 3, 2, 1}

Erasing Elements

Using erase():

vec.erase(vec.begin() + 2);

What happens here:

Removes element at specified position
Shifts remaining elements
Expensive for large vectors (O(n))
Position specified using iterator

Example:

Before: {9, 8, 100, 5, 3, 2, 1}

After erase at index 2: {9, 8, 5, 3, 2, 1}

Clearing Vector

Using clear():

vec.clear();

What happens here:

Removes all elements
Size becomes 0
Capacity may remain (implementation dependent)
O(n) time complexity

Checking Empty:

vec.empty() // Returns true if size is 0

When to Use These Operations

Good fits:

Sorting: when order matters
Reversing: when reverse order needed
Finding: searching for specific values
Inserting: adding at specific positions
Erasing: removing specific elements
Clearing: resetting vector

Performance Considerations:

insert()/erase(): expensive (O(n))
Use sparingly for large vectors
Prefer push_back()/pop_back() when possible
Consider other containers for frequent insert/erase

Important Considerations

Iterators:

begin(): first element
end(): past last element
Used for range operations
Can be incremented/decremented

Performance:

sort(): O(n log n)
reverse(): O(n)
find(): O(n)
insert()/erase(): O(n)
clear(): O(n)

Modifying Operations:

Most operations modify original vector
Make copies if original needed
Be careful with iterator invalidation

return 0;

return 0; closes main and tells the operating system the program finished without an error.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does find return when the value is missing?

Pick an answer to check it.

Question 2

Why is vec.insert(vec.begin(), x) slow on a big vector?

Pick an answer to check it.

Questions people ask

How do I sort in descending order?

sort(vec.begin(), vec.end(), greater<int>()); or sort and then reverse.

How do I remove all copies of a value?

Use the erase-remove idiom: vec.erase(remove(vec.begin(), vec.end(), x), vec.end()); or std::erase(vec, x) in C++20.

Is find fast?

It is a linear scan, O(n). For a sorted vector, binary_search or lower_bound are O(log n).