Templates and Iterators
Completed
Write template <typename It> auto sumRange(It first, It last) that adds the elements in [first, last). Use it on a whole vector of ints, on the first half of it, and on a vector of doubles.
Input
Line 1: n then n ints. Line 2: m then m decimals.
Output
Three lines (the double sum with 2 decimals).
Example
Input
4 1 2 3 4 2 0.5 0.25
Output
10 3 0.75
Editor
C++
Hints
Iterators are what STL algorithms use to describe ranges.
*first - *first is a zero of the right type.
Solution explanation
Writing algorithms against iterators makes them work with any container.
Show solution
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
template <typename It>
auto sumRange(It first, It last) {
auto total = *first - *first;
for (It it = first; it != last; ++it) total += *it;
return total;
}
int main() {
int n, m;
cin >> n;
vector<long long> a(n);
for (auto &x : a) cin >> x;
cin >> m;
vector<double> b(m);
for (auto &x : b) cin >> x;
cout << sumRange(a.begin(), a.end()) << "\n";
cout << sumRange(a.begin(), a.begin() + n / 2) << "\n";
cout << fixed << setprecision(2) << sumRange(b.begin(), b.end()) << "\n";
return 0;
}