Vector Operations

Advanced Vector Operations in C++

IntermediateTopic: STL Containers Programs
Back

C++ Vector Operations Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> vec = {5, 2, 8, 1, 9, 3};
    
    cout << "Original vector: ";
    for (int num : vec) {
        cout << num << " ";
    }
    cout << endl;
    
    // Sort vector
    sort(vec.begin(), vec.end());
    cout << "Sorted vector: ";
    for (int num : vec) {
        cout << num << " ";
    }
    cout << endl;
    
    // Reverse vector
    reverse(vec.begin(), vec.end());
    cout << "Reversed vector: ";
    for (int num : vec) {
        cout << num << " ";
    }
    cout << endl;
    
    // Find element
    auto it = find(vec.begin(), vec.end(), 5);
    if (it != vec.end()) {
        cout << "Element 5 found at index: " << distance(vec.begin(), it) << endl;
    }
    
    // Insert element
    vec.insert(vec.begin() + 2, 100);
    cout << "\nAfter inserting 100 at index 2: ";
    for (int num : vec) {
        cout << num << " ";
    }
    cout << endl;
    
    // Erase element
    vec.erase(vec.begin() + 2);
    cout << "After erasing element at index 2: ";
    for (int num : vec) {
        cout << num << " ";
    }
    cout << endl;
    
    // Clear vector
    vec.clear();
    cout << "\nSize after clear: " << vec.size() << endl;
    cout << "Is empty: " << (vec.empty() ? "Yes" : "No") << endl;
    
    return 0;
}
Output
Original vector: 5 2 8 1 9 3
Sorted vector: 1 2 3 5 8 9
Reversed vector: 9 8 5 3 2 1
Element 5 found at index: 2

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

Size after clear: 0
Is empty: Yes

Understanding Vector Operations

This program teaches you how to perform Advanced Vector Operations in C++. Vectors support various operations like sorting, reversing, finding, inserting, and erasing elements. These operations use iterators to traverse and manipulate elements efficiently.

---

1. What This Program Does

The program demonstrates advanced vector operations:

Sorting elements using sort()
Reversing vector using reverse()
Finding elements using find()
Inserting elements at specific positions
Erasing elements from vector
Clearing entire vector

These operations enable powerful vector manipulation.

---

2. Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <vector>
Provides vector container class.
3.#include <algorithm>
Provides algorithms like sort(), reverse(), find().

---

3. 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

---

4. Sorting Vector

Using sort()

:

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

How it works

:

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}

---

5. Reversing Vector

Using reverse()

:

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

How it works

:

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}

---

6. Finding Elements

Using find()

:

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

How it works

:

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()) {

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

} else {

// Element not found

}

---

    // Element found

7. Inserting Elements

Using insert()

:

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

How it works

:

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}

---

8. Erasing Elements

Using erase()

:

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

How it works

:

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}

---

9. Clearing Vector

Using clear()

:

vec.clear();

How it works

:

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

---

10. When to Use These Operations

Best For

:

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

---

11. 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

---

12. return 0;

This ends the program successfully.

---

Summary

Vector operations: sort(), reverse(), find(), insert(), erase(), clear().
Iterators (begin(), end()) used for range operations.
find() returns iterator, end() if not found.
insert()/erase() can be expensive (O(n)) for large vectors.
Understanding vector operations enables powerful data manipulation.
Essential for algorithms, sorting, and dynamic data management.

This program is fundamental for learning advanced STL operations, understanding iterators, and preparing for complex algorithms and data manipulation in C++ programs.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Vector Operations

This C++ program is part of the "STL Containers Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents