反转每个单词在一个句子中使用c++需要代码优化我的代码片段
Reverse each word in a sentence using C++ need code optimization for my code snippet
我有下面的句子
"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();
}
如果(且仅当)分析代码显示这是一个瓶颈,我会担心将其更改为其他"更有效"的内容。
相关文章:
- C和C 中的代码优化
- 使用清理代码优化多个出口点
- 在 c++ 中从 txt 文件中提取条目的代码优化问题
- 为什么传递值参数经常使编译器更容易进行代码优化
- 来自MATLAB的代码优化直方图C
- C - 代码优化
- 代码优化子集总和
- 在代码优化过程中,C++11编译器是否会在可能的情况下将局部变量转换为右值
- C++-筛选Atkin代码优化
- 协议缓冲区 GetRepeatedField (反射) 代码优化
- C++代码优化
- 编译和代码优化
- C++ ARM 设备上代码优化的提示
- 我是否应该将 const 用于局部变量以获得更好的代码优化
- 用于并行计算的C++代码优化示例
- gcc/C++:如果CPU负载很低,那么代码优化用处不大,这是真的
- 反转每个单词在一个句子中使用c++需要代码优化我的代码片段
- 是我的编译器将适当的代码优化为无用的崩溃代码
- Arduino代码优化的多路复用LED矩阵
- 在代码优化中使用new运算符是否值得?