如何在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 红包祝福语简短10字
18 周六早晨祝福语简短