Vectors and sort in C++
Read numbers into a vector, sort them and find the largest. Press Run to try it, then change the code and run it again.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cout << "How many numbers? ";
cin >> n;
vector<int> v(n);
cout << "Enter them: ";
for (int &x : v) cin >> x;
sort(v.begin(), v.end());
cout << "Sorted: ";
for (int x : v) cout << x << ' ';
cout << "\nLargest: " << *max_element(v.begin(), v.end()) << '\n';
}
Output
Press Run to see the output.
More C++ examples
- Hello, World · The classic first C++ program.
- Classes and objects · A class with a constructor, private data and member functions.
- Count words with a map · Use std::map to count how often each word appears.
- Binary search · Find a value in a sorted array in O(log n) steps.
- Competitive programming template · Fast input and output with bits/stdc++.h, ready for contest problems.