前置std :: string

时间:2011-12-12 00:15:10

标签: c++ string prepend

前缀std::string的最有效方法是什么?是否值得写出一个完整的功能,或者它只需要1-2行?我没有看到任何与std::string::push_front相关的内容。

4 个答案:

答案 0 :(得分:69)

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


Documentation of 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删除重新分配部分来获得一些性能优势(以便在事先分配更多内存)。 / p>

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

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


如果你有一个缓冲区,你知道你 prepend 数据比你追加更频繁,一个好的选择是向后存储字符串,并在需要时将其反转(如果这种情况更为罕见)。

答案 1 :(得分:6)

myString.insert(0, otherString);

让标准模板库编写者担心效率;利用他们所有的工作时间,而不是重新编程轮子。

这种方式都可以。

只要你正在使用的STL实现被认为你将拥有有效的代码。如果您使用写得不好的STL,那么无论如何都会遇到更大的问题:)

答案 2 :(得分:4)

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

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

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

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

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

你应该注意到,虽然这样做效率很低。

答案 3 :(得分:3)

有一个超载的string operator+ (char lhs, const string& rhs);,因此您可以your_string 'a' + your_string来模仿push_front

这不是就地,但会创建一个新的字符串,所以不要期望它有效。对于(可能)更有效的解决方案,使用resize来收集空间,std::copy_backward将整个字符串向后移一个并在开头插入新字符。