反转每个单词在一个句子中使用c++需要代码优化我的代码片段

Reverse each word in a sentence using C++ need code optimization for my code snippet

本文关键字:c++ 代码优化 片段 代码 我的 句子 单词 一个      更新时间:2023-10-16

我有下面的句子

"Where are you going"

我希望每个单词在句子中颠倒过来,如下所示

"erehW era uoy gniog"

提前感谢。

       #include "stdafx.h"
            #include "conio.h"
            #include <string.h>
            #include <iostream>
            using namespace std;

//反向功能
             void reverse(char* sentence)
            {
                int hold, index = 0;

//这里我们调用while loop

                while (index >= 0)
                {

//循环语句直到null结束

                    while ( sentence[index] != ' ')
                    {
                        if(sentence[index] == '')
                            break;
                         index++;
                    }            
             hold = index + 1;  
                index--; 
                    /*
    In your original code,
    This while loop(below) will continue to keep decrementing index 
    even below `0`,You wont exit this while loop until you encounter a ` `.
    For the 1st word of the sentence you will never come out of the loop.
    Hence the check, index>=0
    */
                    while (index >= 0 && sentence[index] != ' ')
                    {
                        cout << sentence[index]; 
                        index--;
                    }
                    cout<<" ";
                    index = hold; 
                    if(sentence[hold-1] == '')
                    {
                        index = -1;
                    }
                }
            }
//main function
            int main()
            {
                char* sentence = new char[256];
                cin.getline(sentence, 256);
                reverse(sentence);
                delete[] sentence; // Delete the allocated memory
            }

对于这样的任务,处理器基本上保证是I/O受限的,几乎不管您执行反转本身有多慢(在这种情况下,从主存读取/写入算作I/O)。

因此,主要的优化是保持代码尽可能的简单和可读。考虑到这一点,我将这样开始:
std::string reverse_words(std::string const &input) {
    std::istringstream buffer(input);
    std::ostringstream result;
    std::transform(std::istream_iterator<std::string>(buffer),
        std::istream_iterator<std::string>(),
        std::ostream_iterator<std::string>(result, " "),
        [](std::string const &in) { return std::string(in.rbegin(), in.rend()); });
    return result.str();
}

如果(且仅当)分析代码显示这是一个瓶颈,我会担心将其更改为其他"更有效"的内容。