My problem is rather simple: I have a dynamic array of objects that have a method returning a string. I want to concatenate all these strings together.
If I had an array of strings instead of objects with a method returning a string, this would be a trivial task:
std::vector<std::string> v{ "f", "o", "o" };
std::string const x = std::accumulate(v.begin(), v.end(), std::string());
But in my case it rather looks like this:
struct foo
{
foo(std::string const & name) : name_(name) {}
std::string const & name() const { return name_; }
private:
std::string const name_;
};
std::vector<foo> v{ foo("f"), foo("o"), foo("o") };
I would like to use the standard library algorithms as I am sure that those are efficient and something that I don't have to debug, but this is too hard to read and understand:
std::vector<std::string> transformed(v.size());
std::transform(v.begin(), v.end(), transformed.begin(),
[](foo const & f) { return f.name(); });
std::string const x = std::accumulate(transformed.begin(), transformed.end(),
std::string());
The future maintainers would probably (and rightfully so) hunt me down to punch me in the face for needlessly complicating an easy task, that could have been done with:
std::string x;
for(auto const & f : v)
x += f.name();
Is there something easier here that I am not seeing, or is this indeed the case where one should let the standard libraries rest, and use the for loop (which is what accumulate boils down to anyway)?