Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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 :

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, ""));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading