Vector Operations
Advanced Vector Operations in C++
IntermediateTopic: STL Containers Programs
C++ Vector Operations Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#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
Vectors support various operations: sort(), reverse(), find(), insert(), erase(), clear(). Iterators (begin(), end()) are used to traverse and manipulate elements. The find() function returns an iterator; if element not found, it returns end(). insert() and erase() can be expensive for large vectors as they may require shifting elements.
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.