Challenge: Template Total
Completed
Write a function template T total(const vector<T>& v) that adds up all items. Read n integers and print their total, then read m decimals and print their total.
Input
n, then n integers; then m, then m decimals.
Output
Two lines: the integer total and the decimal total.
Example
Input
3 1 2 3 2 0.5 0.25
Output
6 0.75
Editor
C++
Hints
template <typename T> goes on the line above the function.
T sum = T(); starts at zero for numbers.
Solution explanation
One template works for both vector<int> and vector<double>; C++ creates each version for you.
Show solution
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
T total(const vector<T>& v) {
T sum = T();
for (const T& x : v) {
sum += x;
}
return sum;
}
int main() {
int n;
cin >> n;
vector<int> a(n);
for (int& x : a) cin >> x;
int m;
cin >> m;
vector<double> b(m);
for (double& x : b) cin >> x;
cout << total(a) << "\n";
cout << total(b) << "\n";
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module