如何在C ++ STL中反转向量元素?
给定一个向量,我们必须使用C++STL程序反转它们的元素。
反转向量
要反转矢量元素,我们可以使用reverse()函数,该函数在C++标准模板库的<algorithm>标头中定义。它接受要执行反向操作的迭代器的范围,并反转给定范围之间的元素。
注意:要使用vector–包含<vector>头文件,而要使用reverse()函数–包含<algorithm>头文件,或者我们可以简单地使用<bits/stdc++。h>头文件。
语法:
reverse(iterator start, iterator end);
在这里,start_position,迭代器end_position是指向容器中要反转的开始和结束元素的迭代器。
示例
Input:
vector<int> v1{ 10, 20, 30, 40, 50, 25, 15 };
reverse(v1.begin(), v1.end());
Output:
15, 25, 50, 40, 30, 20, 10C++STL程序反转向量元素
//C++STL程序反转向量元素
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
//向量
vector<int> v1{ 10, 20, 30, 40, 50 };
//打印元素
cout << "before reversing vector elements..." << endl;
for (int x : v1)
cout << x << " ";
cout << endl;
//反转向量的所有元素
reverse(v1.begin(), v1.end());
//打印元素
cout << "after reversing vector elements..." << endl;
for (int x : v1)
cout << x << " ";
cout << endl;
return 0;
}输出结果
before reversing vector elements... 10 20 30 40 50 after reversing vector elements... 50 40 30 20 10
热门推荐
10 五一公司放假祝福语简短
11 追星女孩的祝福语简短
12 给长辈端午祝福语 简短
13 生日祝福语有诗意简短
14 团圆日祝福语简短
15 中秋商务祝福语简短最新
16 温暖文艺简短祝福语短句
17 男孩上学祝福语简短的
18 入住酒店文案祝福语简短