C++ Transform and Accumulate
Transform and accumulate are algorithms that change values or combine values into one result. Transform builds new values, and accumulate folds values into a single total.
Doubling into a second vector
std::transform applies the named function to each value. The doubled results land in a second vector, and the first vector stays unchanged.
#include <iostream>
#include <vector>
#include <algorithm>
int doubled(int value) {
return value * 2;
}
int main() {
std::vector<int> values = {3, 5, 7, 9};
std::vector<int> results(4);
std::transform(values.begin(), values.end(), results.begin(), doubled);
for (int value : results) {
std::cout << value << "\n";
}
return 0;
}A sum and a sentence
std::accumulate adds the numbers starting from 0. A second call joins the text pieces starting from an empty string.
#include <iostream>
#include <string>
#include <vector>
#include <numeric>
int main() {
std::vector<int> numbers = {10, 20, 30, 40};
int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
std::cout << "Sum: " << sum << "\n";
std::vector<std::string> words = {"One ", "two ", "three"};
std::string sentence = std::accumulate(words.begin(), words.end(), std::string(""));
std::cout << "Sentence: " << sentence << "\n";
return 0;
}Transform in place
The same vector serves as input and output here. Each value grows by 10 inside the vector itself.
#include <iostream>
#include <vector>
#include <algorithm>
int addTen(int value) {
return value + 10;
}
int main() {
std::vector<int> values = {5, 15, 25};
std::transform(values.begin(), values.end(), values.begin(), addTen);
for (int value : values) {
std::cout << value << "\n";
}
return 0;
}Example
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
int withTax(int price) {
return price + price / 10;
}
int main() {
std::vector<int> prices = {20, 30, 50};
std::vector<int> taxed(3);
std::transform(prices.begin(), prices.end(), taxed.begin(), withTax);
for (int price : taxed) {
std::cout << price << "\n";
}
int total = std::accumulate(taxed.begin(), taxed.end(), 0);
std::cout << "Total: " << total << "\n";
return 0;
}Key points
- std::transform reads each value and writes the result of a named function.
- The output range of std::transform can be a second vector.
- The output range can also be the same vector, which changes values in place.
- std::accumulate combines values starting from a given start value.
- The #include <numeric> line brings in std::accumulate.
- Accumulating text needs a std::string start value.
In this example, the named function adds a tenth of each price as tax. std::transform writes the taxed prices into a second vector. std::accumulate then adds the taxed prices into a total of 110.
Note
The type of the start value sets the type of the accumulate result.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does std::accumulate need as its third argument?