C++ / Guided lesson
Explore C++ Vectors and STL Algorithms
Strengthen your C++ programming skills through arrays, pointers, references, vectors, object-oriented programming, and Standard Template Library algorithms.
Browse all C++ topicsWorked example
C++ is a compiled, general-purpose programming language. The Standard Template Library (STL) provides containers and algorithms. A vector is a dynamic array, and std::sort() arranges elements in a specified order.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> numbers = {50, 20, 80, 10, 40};
sort(numbers.begin(), numbers.end());
cout << "Sorted Numbers: ";
for (int number : numbers) {
cout << number << " ";
}
cout << endl;
return 0;
}Expected output
Sorted Numbers: 10 20 40 50 80Check your understanding
What is the difference between an array and a vector in C++?
Show answer
A built-in C++ array has a fixed size determined at creation. A std::vector is a dynamic container that can grow or shrink during execution. Vectors provide useful methods such as push_back(), size(), and pop_back().
Try it yourself
Modify the program to sort the numbers in descending order using the STL sort() function.
Show solution
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
int main() {
vector<int> numbers = {50, 20, 80, 10, 40};
sort(numbers.begin(), numbers.end(), greater<int>());
for (int number : numbers) {
cout << number << " ";
}
return 0;
}
// Output: 80 50 40 20 10