连接C++中类方法提供的字符串

mel*_*el- 3 c++ string algorithm stl c++11

我的问题很简单:我有一个动态的对象数组,它有一个返回字符串的方法.我想将所有这些字符串连接在一起.

如果我有一个字符串数组而不是一个方法返回一个字符串的对象,这将是一个简单的任务:

std::vector<std::string> v{ "f", "o", "o" };
std::string const x = std::accumulate(v.begin(), v.end(), std::string());
Run Code Online (Sandbox Code Playgroud)

但就我而言,它看起来像这样:

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") };
Run Code Online (Sandbox Code Playgroud)

我想使用标准库算法,因为我确信这些算法是有效的,而且我不需要调试,但这很难阅读和理解:

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());
Run Code Online (Sandbox Code Playgroud)

未来的维护人员可能(并且理所当然地)帮助我打击我,因为不必要地使一项简单的任务复杂化,这可以通过以下方式完成:

std::string x;
for(auto const & f : v)
    x += f.name();
Run Code Online (Sandbox Code Playgroud)

这里有什么比我更容易看到的东西,或者确实是这样的情况下应该让标准库休息,并使用for循环(无论如何积累归结为什么)?

Erb*_*ica 6

如果您坚持使用STL,还有另一个版本std::accumulate:

template< class InputIt, class T, class BinaryOperation >
T accumulate( InputIt first, InputIt last, T init, BinaryOperation op );
Run Code Online (Sandbox Code Playgroud)

然后你的代码就可以了

std::string const x = std::accumulate(v.begin(), v.end(), std::string(),
                         [](std::string a, foo const& b){return a += b.name();});
Run Code Online (Sandbox Code Playgroud)

编辑:也许更多的copy-elision友好声明