c++实现reverse
时间: 2024-09-21 16:04:12 浏览: 55
在C++中,反转一个字符串或数组是非常常见的操作,可以使用多种方法来实现。这里我会展示两种基本的方法:一种是使用双指针法,另一种是使用标准库函数`std::reverse`。
**1. 双指针法(两头指针):**
```cpp
#include <iostream>
#include <string>
void reverseString(std::string& str) {
int start = 0;
int end = str.length() - 1;
while (start < end) {
std::swap(str[start], str[end]);
start++;
end--;
}
}
int main() {
std::string str = "Hello, C++!";
reverseString(str);
std::cout << str << std::endl; // 输出:!C++, olleH
return 0;
}
```
在这个例子中,我们初始化两个指针,一个指向字符串的开始,另一个指向结束。然后交换这两个位置的字符,直到两个指针相遇。
**2. 使用`std::reverse`:**
如果你想利用C++的标准库,可以直接使用`std::reverse`函数:
```cpp
#include <iostream>
#include <algorithm> // 引入算法库
int main() {
std::string str = "Hello, C++!";
std::reverse(str.begin(), str.end());
std::cout << str << std::endl; // 输出:!C++, olleH
return 0;
}
```
这行代码会直接对给定的字符串范围进行反转。
阅读全文
相关推荐


















