程序性能优化---倒置字符串中单词

本文探讨了使用不同方法实现字符串逆序输出的效率对比,通过四种不同的C++函数实现,展示了如何利用堆栈和字符串流优化逆序输出过程,实验结果显示,直接字符处理的方法效率最高。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:

输入 have a nice day

输出 day nice a have

实现:

#include <unistd.h>
#include <iostream>
#include <vector>
#include <sstream>
#include <stack>
using namespace std;
string str = "Have a nice day";
void fun(string &res) {
	stack<string>ss;
	stringstream os(str);
	string word;
	while (os >> word) {
		ss.push(word);
	}
	while (false == ss.empty()) {
		res += ss.top();
		res += " ";
		ss.pop();
	}
}
void fun1(string &res) {
    stack<string>ss;
    stringstream os(str);
    string word;
    while (os >> word) {
        ss.push(word);
    }
	static string blank = " ";
    while (false == ss.empty()) {
        res += ss.top();
        res += blank;
        ss.pop();
    }
}
void fun2(string &res) {
	string word;
    stack<string>ss;
	for (auto &ch : str) {
		if (' ' == ch)  {
			ss.push(word);
			word.clear();
			continue;
		}
		word += ch;
	}
	ss.push(word);
    static string blank = " ";
    while (false == ss.empty()) {
        res += ss.top();
        res += blank;
        ss.pop();
    }
}
void fun3(string &res) {
    char word[64] = "";
	int index = 0;
	int size = str.size();
    for(int i = size - 1;i >= 0;i--) {
		if (' ' != str[i]) {
			word[index++] = str[i];
		}
		else {
			for (int i = index - 1;i >= 0;i--) {
				res += word[i];
			}
			res += str[i];
			index = 0;
		}
	}
	for (int i = index - 1;i >= 0;i--) {
		res += word[i];
	}
}


int main() {
	string res;
	for (int i = 0;i < 1000000;i++) {
		//fun(res);			// 2.05s
		//fun1(res);		// 1.970s
		//fun2(res);		// 1.875s
		fun3(res);			// 0.675s
		res.clear();
	}

    return 0;
}

make.sh

g++ -std=c++17 -g -o Test test.cpp -pthread

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值