C++ reverse()函数用法

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 //方法一 翻转字符串
 6 void method1()
 7 {
 8     string s = "i love acm";
 9     reverse(s.begin(), s.end());
10     cout << s << endl;
11 }
12 
13 //方法二 翻转整形数组
14 void method2()
15 {
16     int n, a[100], l, r; //需要翻转的左边界 右边界
17 
18     cin >> n;
19     for(int i = 1; i <= n; ++i) cin >> a[i];
20     cin >> l >> r;
21 
22     reverse(a + l, a + r + 1); //这里注意 结束的指针是右边界下标加 1
23 
24     for(int i = 1; i <= n; ++i) cout << a[i] << " ";
25     cout<<endl;
26 }
27 
28 signed main()
29 {
30     method1();
31     method2();
32     return 0;
33 }

 

posted @ 2022-02-16 14:09  std&ice  阅读(1284)  评论(0编辑  收藏  举报