reverse c++
时间: 2023-07-23 22:03:02 浏览: 61
C++ 中字符串的反转可以使用 STL 库中的 reverse 函数:
```
#include <algorithm>
#include <string>
std::string str = "Hello, World!";
std::reverse(str.begin(), str.end());
```
也可以手动循环交换字符串的首尾字符:
```
#include <string>
std::string str = "Hello, World!";
int length = str.length();
for (int i = 0; i < length / 2; i++) {
std::swap(str[i], str[length - i - 1]);
}
```
相关问题
c++reverse
在C++中,reverse函数用于反转容器中的元素的顺序。引用\[1\]中给出了几种使用reverse函数的示例。例如,可以使用reverse函数来反转字符串、向量或数组。具体使用方法是将要反转的容器的起始位置和结束位置作为参数传递给reverse函数。引用\[2\]和引用\[3\]中的代码示例展示了如何使用reverse函数来反转向量和字符串。
在引用\[2\]的代码示例中,首先创建了一个整数向量v,并将元素1、2、3添加到向量中。然后使用for循环打印出向量中的元素。接下来,调用reverse函数将向量v中的元素反转。最后,再次使用for循环打印出反转后的向量v的元素,输出结果为3、2、1。
在引用\[3\]的代码示例中,首先创建了一个字符串a,并将字符串"123"赋值给a。然后调用reverse函数将字符串a中的字符反转。最后,打印出反转后的字符串a,输出结果为"321"。
因此,使用C++的reverse函数可以方便地反转容器中的元素的顺序。
#### 引用[.reference_title]
- *1* [C++:reverse函数](https://blog.csdn.net/weixin_46024428/article/details/116094154)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [reverse函数(C++)](https://blog.csdn.net/weixin_51566349/article/details/128459338)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
c++ reverse
Sure! If you want to reverse a string in C, you can use the following code:
```c
#include <stdio.h>
#include <string.h>
void reverseString(char* str) {
int length = strlen(str);
int start = 0;
int end = length - 1;
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
int main() {
char str[] = "Hello, World!";
printf("Original string: %s\n", str);
reverseString(str);
printf("Reversed string: %s\n", str);
return 0;
}
```
This code defines a function `reverseString` that takes a character array (`str`) as input and reverses the string in-place. The `main` function demonstrates how to use this function by reversing the string "Hello, World!" and printing the result.