Let the standard library do the work: a vector and two algorithms.
What to build
A program that stores numbers in a vector and uses sort and reverse on them.
Requirements
- Store the numbers in a
vector<int>withpush_back. - Print the size and the sum.
- Print the numbers in increasing order, then in decreasing order, using
sortandreverse.
Input
The first line has n. The second line has the n numbers.
Output
Four lines: size N, sum S, the increasing order and the decreasing order.
Constraints
1 ≤ n ≤ 1000, and each number is from -1000000 to 1000000.
Example
Input:
5
3 1 4 1 5
Output:
size 5
sum 14
1 1 3 4 5
5 4 3 1 1
Why it works
sort and reverse work on any range given by begin() and end(), so there is no loop to write and no index to get wrong.
Examples
Example 1 · Input
5 3 1 4 1 5
Expected output
size 5 sum 14 1 1 3 4 5 5 4 3 1 1
Example 2 · Input
1 -2
Expected output
size 1 sum -2 -2 -2
Hints
Hint 1
Read the numbers with `push_back`, and add them up in a range-for loop.
Hint 2
`sort(v.begin(), v.end())` puts them in increasing order, and `reverse(v.begin(), v.end())` turns the vector around.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void print(const vector<int>& v) {
for (int x : v) cout << x << " ";
cout << endl;
}
int main() {
int n;
cin >> n;
vector<int> v;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
v.push_back(x);
}
long long sum = 0;
for (int x : v) sum += x;
cout << "size " << v.size() << endl;
cout << "sum " << sum << endl;
sort(v.begin(), v.end());
print(v);
reverse(v.begin(), v.end());
print(v);
return 0;
}
Lesson: The standard library: vector, string, map and sort →