前置 std::string

新手上路,请多包涵

预先 std::string 的最有效方法是什么?是否值得写出整个函数来这样做,还是只需要 1 - 2 行?我没有看到任何与 std::string::push_front 相关的内容。

原文由 zeboidlund 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 567
2 个回答

实际上与不存在的 std::string::push_front 有类似的功能,请参见下面的示例。


std::string::insert 的文档

#include <iostream>
#include <string>

int
main (int argc, char *argv[])
{
  std::string s1 (" world");
  std::string s2 ("ello");

  s1.insert (0,     s2); // insert the contents of s2 at offset 0 in s1
  s1.insert (0, 1, 'h'); // insert one (1) 'h'        at offset 0 in s1

  std::cout << s1 << std::endl;
}

输出:

 hello world


由于在字符串前面添加数据可能需要重新分配和复制/移动现有数据,因此您可以通过使用 std::string::reserve (预先分配更多内存)摆脱重新分配部分来获得一些性能优势。

遗憾的是,数据的复制/移动是不可避免的,除非您定义自己的自定义类,其行为类似于 std::string 分配一个大缓冲区并将第一个内容放在此内存缓冲区的中心。

然后,如果缓冲区足够大,您可以在不重新分配和移动数据的情况下预先添加和附加数据。但是,显然仍然需要从 复制到 _目标_。


如果你有一个缓冲区,你知道你会更频繁地 预先 添加数据而不是 添加 一个好的替代方法是向后存储字符串,并在需要时将其反转(如果这种情况更罕见)。

原文由 Filip Roséen - refp 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您正在使用 std::string::append ,您应该意识到以下是等效的:

 std::string lhs1 = "hello ";
std::string lhs2 = "hello ";
std::string rhs = "world!";

lhs1.append(rhs);
lhs2 += rhs; // equivalent to above
// Also the same:
// lhs2 = lhs2 + rhs;

同样,“前置”将等同于以下内容:

 std::string result = "world";
result = "hello " + result;
// If prepend existed, this would be equivalent to
// result.prepend("hello");

您应该注意到,尽管执行上述操作是相当低效的。

原文由 Mike Bailey 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题