c++ - std string vs char performance,从一开始就删除部分的最佳技术

标签 c++ performance string char std

好吧,我必须处理大量文本,从头到尾对其进行线性分析。我想知道更好的方法是什么:使用 char* 或 std::string。 在使用 char* 时,我可以将指针更改为字符串中更远的位置,例如。

//EDIT later: mallocing some space for text
char str[] = "text to analyse";
char * orig = str;
//process
str += processed_chars; //quite fast
//process again
// later: free(orig);

但使用字符串我可能不得不使用 std::string::erase - 但它会创建一个拷贝,或移动字节或其他东西(我不知道实际的实现)

string str = "text to analyse";
//process
str = str.erase(0,processed_chars);

或者有没有办法改变 std::string 的隐藏指针?

编辑:正如 Sylvain Defresne 在此处请求的更多代码:

class tag {
public:
    tag(char ** pch) {
        *pch = strstr(*pch,"<");
        if(pch == NULL) return;

        char *orig = *pch+1;
        *pch = strstr(*pch,">");
        if(pch == NULL) return;
        *pch+=sizeof(char); //moving behind the >

        //process inner tag data

        if(*(*pch-2)!='/'){// not selfclose
            while (!(**pch == '<' && *(*pch+1) == '/')){ //sarch for closing tag
                tag* kid = new tag(pch);
                sublings.push_back(*kid);
            }

            *pch = strstr(*pch,">");
            if(pch == NULL) return;
            *pch+=sizeof(char); //moving behind the >

            //add check if the clothing tag is matching

        }
    }
}

我将它用于递归类 xml 符号解析

char str[] ="<father><kid /></fatherr>";
char * pch = str;
tag *root = new tag(&pch);

这段代码丑得要死,我只是从低级指针算术和东西开始,直到现在都使用可视化组件所以不要判断得太难

最佳答案

对于 std::string,您可能会使用 std::string::iterator。您的代码将是:

std::string str = "text to analyse";
std::string::iterator iter = str.begin();

// process
iter += processed_chars; 

关于c++ - std string vs char performance,从一开始就删除部分的最佳技术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5327408/

相关文章:

c++ - 编译器和字节序

c++ - 如何将 std::chrono::duration 转换为 boost 持续时间

java 文件相对化方法性能

java - 什么是 Java 字符串实习?

Python - 将字典和键值列表转换为字符串

C++ 两个派生类中有彼此的对象(包括问题)

c++ - C++ 宏可以在 C++ 文件末尾添加一些代码吗?

performance - Go Web 应用程序是否应该在一个模板中包含所有页面?

c# - 为什么我的 StringReader 比 .NET StringReader 慢 50us?

c# - 具有数据库文件相对路径的连接字符串