我想编写一个函数,将 std::string
的任何序列与幕后的 一个 malloc 连接起来。因此,需要首先计算字符串的总长度。该函数需要以这种方式使用:
std::string s0 = ...;
std::string s1 = ...;
std::string s2 = ...;
std::string s = join(s0, s1, s2);
更好的 join
会混合使用 std::string
和 std::string_view
。如果我们可以添加字符串文字会更好。您将如何在 C++11 中编写这样的函数(它需要使用 gcc 4.8.5
和 Visual Studio 2015
进行编译)?
最佳答案
如果你有一个 string_view
类型,那么你可以只接受一个 string_view
的集合,对它们的大小求和,分配,然后复制进来。
std::string join(std::initializer_list<string_view> values)
{
std::string result;
result.reserve(std::accumulate(values.begin(), values.end(), 0, [](string_view s) { return s.length(); }));
std::for_each(values.begin(), values.end(), [&result](string_view s) { result.append(s.data()); });
return result;
}
关于c++ - 连接一个字符串家族,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45876498/