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

时间:2015-10-08 16:52:38

标签: c++ c++11

我有以下句子

"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循环

                while (index >= 0)
                {

//遍历句子,直到空终止

                    while ( sentence[index] != ' ')
                    {
                        if(sentence[index] == '\0')
                            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] == '\0')
                    {
                        index = -1;
                    }
                }
            }
//main function

            int main()
            {

                char* sentence = new char[256];
                cin.getline(sentence, 256);
                reverse(sentence);
                delete[] sentence; // Delete the allocated memory
            }

1 个答案:

答案 0 :(得分:0)

对于这样的任务,处理器基本上保证是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();
}

如果(并且仅当)分析代码时向我显示这是一个瓶颈,我会担心将其更改为其他内容&#34;更高效&#34;。