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.
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;56int main() {7 vector<int> vec = {5, 2, 8, 1, 9, 3};89 cout << "Original vector: ";10 for (int num : vec) {11 cout << num << " ";12 }13 cout << endl;1415 // Sort vector16 sort(vec.begin(), vec.end());17 cout << "Sorted vector: ";18 for (int num : vec) {19 cout << num << " ";20 }21 cout << endl;2223 // Reverse vector24 reverse(vec.begin(), vec.end());25 cout << "Reversed vector: ";26 for (int num : vec) {27 cout << num << " ";28 }29 cout << endl;3031 // Find element32 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 }3637 // Insert element38 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;4445 // Erase element46 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;5253 // Clear vector54 vec.clear();55 cout << "\nSize after clear: " << vec.size() << endl;56 cout << "Is empty: " << (vec.empty() ? "Yes" : "No") << endl;5758 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
Start with {5, 2, 8, 1, 9, 3}.
- 2
sort → 1 2 3 5 8 9.
- 3
reverse → 9 8 5 3 2 1.
- 4
find 5 and print its index with distance → 2.
- 5
insert 100 at index 2, then erase it.
- 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:
Iterators:
Sorting Vector
Using sort():
sort(vec.begin(), vec.end());
What happens here:
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:
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:
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:
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:
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:
Checking Empty:
vec.empty() // Returns true if size is 0
When to Use These Operations
Good fits:
Performance Considerations:
Important Considerations
Iterators:
Performance:
Modifying Operations:
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).