2015-10-08 102 views
-5

反转句子中的每一个字,我有如下句子使用C++需要代码优化我的代码片段

"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

请修复您的代码格式,此问题目前接近无法读取。 – shuttle87

+0

@prakash你为什么认为你需要优化? – LogicStuff

+0

我正在使用这么多循环。它杀死了性能。 – prakash

回答

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(); 
} 

如果(且仅当)给我,这是一个瓶颈,我会担心这种改变别的东西“更高效” 。