如何在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 送给学长毕业祝福语简短