Simplification of appender function using std::accumulate
I wanted a simple function that takes a collection of strings and appends them and returns one string which is each string item appended together. I thought std::accumulate was the way to go but interested to hear if this code could be improved.
Is there a simpler append type function that can be used here instead of the lambda?
Is this overly complicated and best achieved by some other code?
#include <string>
#include <vector>
#include <iostream>
#include <numeric>
std::string concatenate(std::vector<std::string> strings)
{
return std::accumulate(strings.begin(), strings.end(), std::string(""), [](std::string s1, std::string s2) { return s1 + s2; });
}
int main() {
std::vector<std::string> vec2{ "aaa","bbb","ccc","ddd","eee","fff" };
std::cout << concatenate(vec2) << std::endl;
}
Solution 1:
Yes, you can omit the lambda entirely (or use std::plus<>{}
).
Also the ""
can be removed from std::string("")
, or the whole third argument can be removed if you switch to std::reduce
:
std::reduce(strings.begin(), strings.end());
Also concatenate
should take the vector by a const reference, or even better a std::span<const std::string>
(by value).
Also libfmt can be used for this:
fmt::format("{}", fmt::join(strings, ""));
Solution 2:
It can be simplified with C++17 fold expression, there is no an intermediate or a temporary collection needed.
#include <string>
#include <iostream>
template<typename ...S>
std::string concatenate(S&&... strings) {
using namespace std::string_literals;
return (""s + ... + strings);
}
int main() {
std::cout << concatenate("aaa","bbb","ccc","ddd","eee","fff") << std::endl;
}