news 2026/6/23 1:12:44

一天认识一个STL库函数——reverse()

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
一天认识一个STL库函数——reverse()

一、什么是reverse()函数?

reverse()是C++ STL中一个非常有用的算法函数,用于反转序列容器(如vector、list、deque、string等)中元素的顺序。它属于<algorithm>头文件中的算法库,可以高效地将容器中的元素顺序完全颠倒。

二、基本用法

1.反转整个容器

#include <iostream> #include <algorithm> // reverse()函数在这里 #include <vector> using namespace std; int main() { vector<int> numbers = {1, 2, 3, 4, 5}; for (int num : numbers) { cout << num << " "; } cout << std::endl; // 输出: 1 2 3 4 5 // 使用reverse()反转整个vector reverse(numbers.begin(), numbers.end()); for (int num : numbers) { cout << num << " "; } cout << std::endl; // 输出: 5 4 3 2 1 return 0; }

2.反转字符串

#include <iostream> #include <algorithm> #include <string> using namespace std; int main() { string text = "Hello, World!"; // 反转字符串 reverse(text.begin(), text.end()); cout << "反转后: " << text << std::endl; // 输出: !dlroW ,olleH // 判断回文字符串 string palindrome = "racecar"; string original = palindrome; reverse(palindrome.begin(), palindrome.end()); if (original == palindrome) { cout << original << " 是回文字符串!" << endl; } else { cout << original << " 不是回文字符串!" << endl; } return 0; }

3.反转部分元素

#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector<int> numbers = {10, 20, 30, 40, 50, 60, 70}; for (int num : numbers) { cout << num << " "; } cout << endl; // 输出: 10 20 30 40 50 60 70 // 只反转中间部分(第2到第5个元素,索引1到4) reverse(numbers.begin() + 1, numbers.begin() + 5); for (int num : numbers) { cout << num << " "; } cout << endl; // 输出: 10 50 40 30 20 60 70 return 0; }

三、reverse()函数的特点

1.参数:两个迭代器

// 函数签名 template<class BidirIt> void reverse(BidirIt first, BidirIt last); // first: 指向要反转的第一个元素 // last: 指向要反转的最后一个元素的下一个位置

2.时间复杂度:O(n)

  • 需要遍历一半的元素进行交换

  • 对于n个元素,大约需要n/2次交换

3.原地操作

  • reverse()直接在原容器上修改,不创建新容器

  • 不需要额外的内存空间(除了临时变量)

4.支持双向迭代器

  • 需要容器的迭代器支持双向移动(++和--)

  • 适用于vector、deque、list、string等

四、实际应用场景

1.旋转数组

#include <iostream> #include <algorithm> #include <vector> using namespace std; void rotateArray(vector<int>& arr, int k) { int n = arr.size(); k = k % n; // 处理k大于数组长度的情况 if (k == 0) return; // 方法:三次反转法 // 1. 反转整个数组 reverse(arr.begin(), arr.end()); // 2. 反转前k个元素 reverse(arr.begin(), arr.begin() + k); // 3. 反转剩余元素 reverse(arr.begin() + k, arr.end()); } int main() { vector<int> numbers = {1, 2, 3, 4, 5, 6, 7}; cout << "原始数组: "; for (int num : numbers) { cout << num << " "; } cout << endl; // 向右旋转3位 rotateArray(numbers, 3); cout << "旋转3位后: "; for (int num : numbers) { cout << num << " "; } cout << std::endl; // 输出: 5 6 7 1 2 3 4 return 0; }

2.反转单词顺序

#include <iostream> #include <algorithm> #include <string> #include <sstream> #include <vector> using namespace std; string reverseWords(string s) { // 先反转整个字符串 reverse(s.begin(), s.end()); stringstream ss(s); string word, result; vector<std::string> words; // 分割单词 while (ss >> word) { // 反转每个单词(恢复原始顺序) reverse(word.begin(), word.end()); words.push_back(word); } // 重新组合 for (size_t i = 0; i < words.size(); ++i) { if (i > 0) result += " "; result += words[i]; } return result; } int main() { string sentence = "the sky is blue"; cout << "原始句子: " << sentence << endl; cout << "单词反转后: " << reverseWords(sentence) << endl; // 输出: blue is sky the return 0; }

3.数字反转

#include <iostream> #include <algorithm> #include <string> using namespace std; int reverseNumber(int num) { // 处理负数 bool isNegative = num < 0; if (isNegative) num = -num; // 转换为字符串 string numStr = to_string(num); // 反转字符串 reverse(numStr.begin(), numStr.end()); // 转换回整数 int result = stoi(numStr); // 恢复负号 return isNegative ? -result : result; } int main() { int num1 = 12345; int num2 = -6789; cout << num1 << " 反转后: " << reverseNumber(num1) << endl; // 54321 cout << num2 << " 反转后: " << reverseNumber(num2) << endl; // -9876 return 0; }

五、与其他反转方法的比较

1.手动反转

#include <iostream> #include <vector> using namespace std; void manualReverse(vector<int>& vec) { int left = 0; int right = vec.size() - 1; while (left < right) { // 交换元素 swap(vec[left], vec[right]); left++; right--; } } int main() { vector<int> numbers = {1, 2, 3, 4, 5}; cout << "手动反转前: "; for (int num : numbers) { cout << num << " "; } cout << endl; manualReverse(numbers); cout << "手动反转后: "; for (int num : numbers) { cout << num << " "; } cout << endl; return 0; }

2.使用rbegin()和rend()

#include <iostream> #include <vector> using namespace std; int main() { vector<int> numbers = {1, 2, 3, 4, 5}; cout << "反向遍历(不修改原数组): "; for (auto it = numbers.rbegin(); it != numbers.rend(); ++it) { cout << *it << " "; } cout << endl; // 输出: 5 4 3 2 1 cout << "原数组未改变: "; for (int num : numbers) { cout << num << " "; } cout << endl; // 输出: 1 2 3 4 5 return 0; }

六、C++20及后续版本

在C++20中,引入了范围库,可以使用更简洁的语法:

#include <iostream> #include <vector> #include <algorithm> #include <ranges> // C++20 using namespace std; int main() { vector<int> numbers = {1, 2, 3, 4, 5}; // C++20范围视图(不修改原容器) auto reversedView = numbers | std::views::reverse; cout << "使用C++20范围视图反向遍历: "; for (int num : reversedView) { cout << num << " "; } cout << endl; // 输出: 5 4 3 2 1 cout << "原数组未改变: "; for (int num : numbers) { cout << num << " "; } cout << endl; // 输出: 1 2 3 4 5 return 0; }

七、总结&今日题目

reverse()是STL中一个简单但强大的算法函数,用于反转容器中元素的顺序。记住以下要点:

  1. 包含头文件#include <algorithm>

  2. 参数:两个迭代器,表示要反转的范围

  3. 时间复杂度:O(n),进行大约n/2次交换

  4. 原地操作:直接修改原容器

  5. 适用容器:支持双向迭代器的容器(vector、deque、list、string、array等)

  6. 常见用途

    • 反转字符串或数组

    • 判断回文

    • 旋转数组

    • 反转单词顺序

  7. 注意事项

    • 确保迭代器范围有效

    • list有自己的reverse()成员函数,效率更高

    • 使用reverse_copy()如果需要保留原容器

今日题目:回文检查器

问题描述

你正在开发一个文本处理工具,需要检查用户输入的单词或句子是否是回文(palindrome)。回文是指正读和反读都一样的字符串(忽略大小写、空格和标点符号)。

功能要求:

  1. 提示用户输入一个单词或句子

  2. 清理输入(移除空格、标点,转换为小写)

  3. 使用reverse()函数辅助判断是否为回文

  4. 显示判断结果

输入格式

一个字符串(可能包含空格和标点符号)。

输出格式

判断结果和详细的分析过程。

解答:

#include <iostream> #include <algorithm> #include <string> #include <cctype> uisng namesapce std; int main() { string input; getline(cin, input); string cleaned; for (char ch : input) { if (isalnum(ch)) { cleaned += tolower(ch); } } // 使用reverse()判断 string reversed = cleaned; reverse(reversed.begin(), reversed.end()); // 输出结果 cout << "结果: "; if (cleaned == reversed) { cout << "是回文" << endl; } else { cout << "不是回文" << endl; } return 0; }
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/22 21:06:12

CEX开发困局:当达普韦伯为交易所注入“数字灵魂”

深夜三点&#xff0c;你的技术总监发来紧急消息&#xff1a;“又一家二线交易所宣布关闭&#xff0c;这是本月第三例。”你看着自己投入了800万、开发已半年的CEX项目代码库&#xff0c;突然感到一阵寒意——你正在重蹈他们的覆辙。 残酷现实&#xff1a;传统CEX开发的“三重死…

作者头像 李华
网站建设 2026/6/23 18:51:03

AutoGPT镜像集成指南:如何嵌入现有业务系统?

AutoGPT镜像集成指南&#xff1a;如何嵌入现有业务系统&#xff1f; 在企业自动化需求日益增长的今天&#xff0c;一个常见的挑战浮出水面&#xff1a;如何让AI真正“替人干活”&#xff0c;而不是仅仅回答问题&#xff1f;传统的脚本或RPA工具虽然能完成固定流程&#xff0c;…

作者头像 李华
网站建设 2026/6/23 6:06:51

AutoGPT项目活跃度分析:GitHub星标增长趋势

AutoGPT项目活跃度分析&#xff1a;GitHub星标增长趋势 在生成式AI浪潮席卷全球的今天&#xff0c;一个名为AutoGPT的开源项目悄然走红。它不像ChatGPT那样以流畅对话吸引大众眼球&#xff0c;也没有Sora凭借视频生成惊艳世人&#xff0c;但它却在开发者社区掀起了一场静默革命…

作者头像 李华
网站建设 2026/6/23 11:44:40

AutoGPT能否生成短视频脚本?内容创作新方式

AutoGPT能否生成短视频脚本&#xff1f;内容创作新方式 在抖音、B站、YouTube Shorts等平台的推动下&#xff0c;短视频已成为信息传播的主战场。每天有数以亿计的内容被上传&#xff0c;而背后的创作者却常常面临一个共同困境&#xff1a;创意枯竭、节奏难控、资料搜集耗时——…

作者头像 李华
网站建设 2026/6/23 18:51:12

超越ChatGPT!教你开发能自主完成复杂任务的AI智能体,代码开源

&#x1f44b; 你好&#xff0c;我是 daner。 一个美好得故事 今天认识了Agent 一、一句话总结 在探索任何一个复杂概念时&#xff0c;我们最好从一个简洁的定义开始。在人工智能领域&#xff0c;智能体被定义为任何能够通过传感器&#xff08;Sensors&#xff09;感知其所处环…

作者头像 李华