我的问题很简单:我有一个动态对象数组 方法返回一个字符串。我想将所有这些字符串连接在一起。
如果我有一个字符串数组而不是对象,并且方法返回一个 字符串,这将是一项微不足道的任务:
std::vector<std::string> v{ "f", "o", "o" };
std::string const x = std::accumulate(v.begin(), v.end(), std::string());
但在我的例子中,它看起来像这样:
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") };
我想使用标准库算法,因为我确信它们是 高效而且我不需要调试,但这太难读了 并理解:
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());
future 的维护者可能会(理所当然地)追捕我来打击我 我因为不必要地使一项简单的任务复杂化而受到指责,那本来可以 完成:
std::string x;
for(auto const & f : v)
x += f.name();
这里有没有我没有看到的更简单的东西,或者确实是这样 人们应该让标准库休息的地方,并使用 for 循环(这是 积累归结为什么)?
最佳答案
如果你坚持要用STL,还有一个版本的std::accumulate
:
template< class InputIt, class T, class BinaryOperation >
T accumulate( InputIt first, InputIt last, T init, BinaryOperation op );
那么你的代码就可以变成
std::string const x = std::accumulate(v.begin(), v.end(), std::string(),
[](std::string a, foo const& b){return a += b.name();});
编辑:也许对复制省略更友好的声明
关于c++ - 连接由 C++ 中的类方法提供的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19365019/