如果您以某种方式想到托管领域中的 StringBuilder。
您可以使用 Alphabet (Google) Library、ABCLib、ABCL 或只是 Abseil。
Abseil's Strings library 向前看并立即分配所需的所有内容,然后根据需要在其中构建字符串。对于 concat 作业,您只需要 absl::StrCat() 和 absl::StrAppend()。
我不擅长解释事情。也许下面这个godbolt 链接可能比我说得更好。
godbolt.org/g/V45pXJ
在 YouTube 上了解更多信息:CppCon 2017: Titus Winters “Hands-On With Abseil”(ffw 至 32 分钟)
youtube.com/watch?v=xu7q8dGvuwk&t=32m
#include <string>
#include <iostream>
#include <absl/strings/str_cat.h>
int main()
{
std::string s1,s2,s3,s4,
s5,s6,s7,s8,
s9,s10,s11,s12;
std::getline(std::cin, s1);
std::getline(std::cin, s2);
std::getline(std::cin, s3);
std::getline(std::cin, s4);
std::getline(std::cin, s5);
std::getline(std::cin, s6);
std::getline(std::cin, s7);
std::getline(std::cin, s8);
std::getline(std::cin, s9);
std::getline(std::cin, s10);
std::getline(std::cin, s11);
std::getline(std::cin, s12);
std::string s = s1 + s2 + s3 + s4 + // a call to operator+ for each +
s5 + s6 + s7 + s8 +
s9 + s10 + s11 + s12;
// you shall see that
// a lot of destructors get called at this point
// because operator+ create temporaries
std::string abseil_s =
absl::StrCat(s1,s2,s3,s4, // load all handles into memory
s5,s6,s7,s8, // then make only one call!
s9,s10,s11,s12);
return s.size() + abseil_s.size();
// you shall see that
// only "real" s1 - s12 get destroyed
// at these point
// because there are no temporaries!
}
2021 年更新
今天,当 c++20 library 实现完成时,您可以选择使用 fmt:format 或 std::format。 (当前 fmtlib 现在支持 c++14。)
format 会像 Abseil StrCat 一样向前看,所以不会浪费临时工。
string fmt_s =
fmt::format("{}{}{}{}{}{}{}{}{}{}{}{}",
s1,s2,s3,s4, // load all handles into memory
s5,s6,s7,s8, // then make only one call!
s9,s10,s11,s12);
[LIVE]