C++ 处理字符串的sstream vs for循环速度

C++ 处理字符串的sstream vs for循环速度,c++,performance,sstream,C++,Performance,Sstream,我想知道sstream处理字符串是否比for循环快? 例如,假设我们有一个字符串,我们无法将其仅用于分隔单词: std::string somestring = "My dear aunt sally went to the market and couldn't find what she was looking for"; 字符串流会更快吗?它绝对更漂亮 std::string temp; stringstream input(somestring); while(in

我想知道sstream处理字符串是否比for循环快? 例如,假设我们有一个字符串,我们无法将其仅用于分隔单词:

std::string somestring = "My dear aunt sally went to the market and couldn't find what she was looking for";
字符串流会更快吗?它绝对更漂亮

std::string temp;
stringstream input(somestring);
while(input >> temp){
  std::cout << temp;
}
std::字符串温度;
stringstream输入(somestring);
同时(输入>>温度){

std::cout您将问题标记为
性能
,但未指定“处理字符串”的详细信息

您需要将单词复制到另一个存储器中吗?还是仅仅为了识别它们?在两个示例中,复制将占用大部分时间


不用说,您不应该在性能关键代码:)中使用
std::cout

sstream vs for循环速度来处理字符串。对于优化/发布版本,它可能没有多大区别。您可以使用相同的字符串对每个字符串计时。确保字符串至少有几KB。可以帮助您回答这些问题uestions.显示循环更快(假设我做得对)@jrubix它们都循环,但对于相同的输入,两者有时有不同的输出,这意味着一个有bug。这就是我们通常说使用标准库的原因,因为它们是已知工作的。您自己编写的代码更可能包含bug。
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;