0

I was wondering wether sstream is faster than just a for loop for processing a string? say for example we have a string that we can't to separate just the words:

std::string somestring = "My dear aunt sally went to the market and couldn't find what she was looking for";

would a string stream be faster? Its definitely prettier.

std::string temp;
stringstream input(somestring);
while(input >> temp){
  std::cout << temp;
}

or utilizing a regular old for loop and a buffer?

std::string buffer; //word buffer
    for(int i= 0; i < somestring.size(); ++i){
        if(somestring.at(i) == 32 && buffer == ""){
            continue;
        }
        if(somestring.at(i) == 32 || somestring.at(i) == '\n'){
            std::cout << buffer;
            buffer.clear();
            continue;
        }
        buffer += somestring.at(i);
    }
    std::cout << buffer;

tldr: I guess i'm mainly wondering if sstream is more optimized and faster at processing a string than just a regular for loop?

EDIT: Edited the forloop

4

1 回答 1

1

您用 标记了您的问题performance,但没有指定“处理字符串”的详细信息。

您是否需要将单词复制到不同的存储空间?还是只是为了识别它们?在您的两个示例中,复制将花费大部分时间。

不用说,你不应该有std::cout性能关键的代码:)

于 2021-02-26T21:54:11.033 回答