zeb*_*und 50 c++ string prepend
什么是最有效的前置方式std::string?是否值得写出一个完整的功能,或者它只需要1-2行?我没有看到任何与之相关的内容std::string::push_front.
Fil*_*efp 75
实际上存在与不存在的功能类似的功能std::string::push_front,请参见下面的示例.
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
hello world
Run Code Online (Sandbox Code Playgroud)
由于在数据字符串前面添加数据可能需要重新分配和复制/移动现有数据,因此可以通过使用std::string::reserve(手动分配更多内存)来删除重新分配部分,从而获得一些性能优势.
数据的复制/移动是不可避免的,除非您定义自己的自定义类,其行为类似于std::string分配大缓冲区并将第一个内容放在此内存缓冲区的中心.
然后,如果缓冲区足够大,您可以在不重新分配和移动数据的情况下预先添加和附加数据.显然,仍然需要从源复制到目的地.
如果你有,你知道你会缓冲预先考虑往往比你的数据追加一个很好的选择是存储字符串倒退,并在需要时扭转它(如果是较为少见).
myString.insert(0, otherString);
Run Code Online (Sandbox Code Playgroud)
让标准模板库编写者担心效率; 利用他们所有的工作时间,而不是重新编程车轮.
这样做可以做到这两点.
只要你正在使用的STL实现被认为你将拥有有效的代码.如果你使用写得不好的STL,那么无论如何你都有更大的问题:)
如果您使用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;
Run Code Online (Sandbox Code Playgroud)
同样,“ prepend”将等效于以下内容:
std::string result = "world";
result = "hello " + result;
// If prepend existed, this would be equivalent to
// result.prepend("hello");
Run Code Online (Sandbox Code Playgroud)
您应该注意,尽管执行上述操作效率不高。
| 归档时间: |
|
| 查看次数: |
60722 次 |
| 最近记录: |