📚 Vector Operations in C++: Sorting and Searching
Vectors in C++ (from the Standard Template Library) are dynamic arrays that allow you to store and manipulate elements easily. In this tutorial, we will explore how to perform sorting and searching operations using std::vector
.
📘 What is a Vector in C++?
A vector is a sequence container that encapsulates dynamic size arrays. Unlike regular arrays, vectors can grow and shrink dynamically.
🔍 Searching in Vector
Searching in a sorted vector can be done using the binary_search()
function in the <algorithm>
header. It returns true if the element is found.
⬇️ Sorting a Vector
Use the sort()
function from the <algorithm>
header to sort a vector in ascending or descending order.
📄 C++ Example: Sorting & Searching with Vector
#include <iostream>
#include <vector>
#include <algorithm> // for sort() and binary_search()
using namespace std;
int main() {
vector<int> nums = {40, 10, 30, 20, 50};
cout << "Original vector: ";
for (int num : nums)
cout << num << " ";
cout << endl;
// Sort in ascending order
sort(nums.begin(), nums.end());
cout << "Sorted vector: ";
for (int num : nums)
cout << num << " ";
cout << endl;
// Search for an element
int target = 30;
if (binary_search(nums.begin(), nums.end(), target))
cout << target << " found in the vector." << endl;
else
cout << target << " not found in the vector." << endl;
return 0;
}
📝 Sample Output
Sorted vector: 10 20 30 40 50
30 found in the vector.
🧠 How It Works
vector<int> nums
creates a dynamic array of integers.sort(nums.begin(), nums.end())
sorts the vector in ascending order.binary_search()
checks if a number exists in the sorted vector.- STL functions like
sort
andbinary_search
simplify common operations.
These vector operations are efficient and widely used in competitive programming and software development. Mastering them is essential for any C++ developer.
Post a Comment