实现翻转数组,字符串,向量!
1翻转数组
//头文件 #include <algorithm> //使用方法 reverse(a, a+n);//n为数组中的元素个数
讯享网
示例代码,
讯享网#include <iostream> #include <algorithm> using namespace std; void MyShow(int a[], int n) {
for(int i = 0; i < n; i++) cout << a[i] << ' '; cout << endl; } int main() {
int a[5] = {
1, 2, 3, 4, 5}; //1 显示未翻转的数组内容 MyShow(a, 5); //2 翻转数组然后再显示 reverse(a, a+5); MyShow(a, 5); return 0; }
输出为,
1 2 3 4 5 5 4 3 2 1
2翻转字符串
讯享网//用法为 reverse(str.begin(), str.end());
示例代码为,
#include <iostream> #include <algorithm> using namespace std; int main() {
string str = "abcdefg"; //1 显示未翻转的字符串 cout << str << endl; //2 翻转数组,然后显示 reverse(str.begin(), str.end()); cout << str << endl; return 0; }
输出为,
讯享网abcdefg gfedcba
3翻转向量
//用法 reverse(vec.begin(), vec.end());
示例代码为,
讯享网#include <iostream> #include <algorithm> #include <vector> using namespace std; void MyShow(vector<int> num) {
for(int i = 0; i < num.size(); i++) cout << num[i] << ' '; cout << endl; } int main() {
vector<int> vec = {
1, 2, 3, 4, 5}; //1 显示未翻转的向量 MyShow(vec); //2 翻转数组然后再显示 reverse(vec.begin(), vec.end()); MyShow(vec); return 0; }
输出为,
1 2 3 4 5 5 4 3 2 1

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/118698.html