【发布时间】:2017-06-07 11:17:05
【问题描述】:
我有一个输入字符串,我将使用它来构建一个输出字符串。输出字符串与输入字符串大致相同,但沿途有一些细微的变化,这取决于我们是否在输入中点击了某些字符。代码是这样的
outputTree(std::ostream& o, const char* input) {
size_t len = strlen(input);
int indent = 0;
string output;
for(size_t i = 0; i < input_len; i++) {
if(input[i] == '(') {
indent++;
output.append(1,'\n');
for(int j = 0; j < indent; j++) {
output.append(" ");
}
}
if(input[i] == ')') {
output.append(1,'\n');
for(int j = 0; j < indent; j++) {
output.append(" ");
}
indent--;
}
output.append(1,input[i]);
}
o << output << endl;
}
虽然这可行,但逐个字符执行此操作非常慢。谁能推荐一些更好的方法(使用标准功能,即没有提升)?
【问题讨论】:
-
如果代码有效,那么我建议您在codereview.stackexchange.com 上进行审核。
-
作为一个快速建议,
for(int j = 0; j < indent; j++) { output.append(" "); }部分可以移动到单独的函数中 -
你写信给
output是为了什么?直接写信给o,好多了。此外,您也可以直接从istream阅读。 -
is pretty slow- 你是如何测量的?您是否尝试过优化构建? -
我投票决定将此问题作为题外话结束,因为它是Code Review。
标签: c++ string algorithm optimization