【发布时间】:2014-12-11 07:24:42
【问题描述】:
我想在 C++ 中填充 string,
原来只是直接在字符串末尾加上\0。
paddingstr = "test";
for (int index = 0; index < 20000*1024; ++index){
paddingstr += '\0';
}
然后我找到了几种方法来实现我的目标,它们是
- add-leading-zeros-to-string-without-sprintf
- padding-stl-strings-in-c
- c-can-setw-and-setfill-pad-the-end-of-a-string
我想知道哪种方法最有效。然后我比较它们。
string paddingstr = "test";
__int64 before_run_t = GetTimeMs64();
string afterpadding = paddingstr.append(string(20000*1024, '\0'));
cout << "The run time of append is " << GetTimeMs64() - before_run_t << endl;
paddingstr = "test";
before_run_t = GetTimeMs64();
paddingstr.insert(paddingstr.end(), 20000*1024, '\0');
cout << "The run time of insert is " << GetTimeMs64() - before_run_t << endl;
paddingstr = "test";
before_run_t = GetTimeMs64();
for (int index = 0; index < 20000*1024; ++index){
paddingstr += '\0';
}
cout << "The run time of adding is " << GetTimeMs64() - before_run_t << endl;
ostringstream ss;
before_run_t = GetTimeMs64();
ss << 't' << std::setw(20000*1024) << std::setfill('a') << '\0';
paddingstr = ss.str();
cout << "The run time of ostream is " << GetTimeMs64() - before_run_t << endl;
结果是
The run time of append is 60
The run time of insert is 3
The run time of adding is 8589
The run time of ostream is 2276
我的问题是为什么插入是最快的?
更新:测试代码从
ss << 't' << std::setw(20000*1024) << std::setfill('\0');
paddingstr = ss.str();
因为\0是在字符串后面填充,而函数str()只是将t返回到paddingstr,所以测试结果不正确。
【问题讨论】:
-
为什么要将
append调用的结果分配给一个新字符串? -
如果
\0在原始字符串之后填充,那么ss.str()只返回字符串t而不是填充字符串。