在C ++中使用STL处理数组和向量
在解决问题的竞争性编程中,数组和向量是非常重要的数据结构。而且c++编程中的STL(标准模板库)提供了一些用于执行数组和向量运算的功能。
让我们看看其中的一些功能,
查找数组/向量的和,最小值和最大值-在STL中,有一些函数可以帮助您查找数组/向量的和,最大值和最小值。具有功能的功能,
求和
accumulate(startIndex, endIndex, initialSum)
数组/vecto的最大元素
*max_element(startIndex, endIndex)
数组/向量的最小元素
*min_element(startIndex, endIndex)
在数组上执行操作的程序-
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
int array[] = {65, 7,12, 90, 31, 113 };
int l = sizeof(array) / sizeof(array[0]);
cout<<"数组的元素是: ";
for(int i = 0; i<l; i++)
cout<<array[i]<<"\t";
cout<<endl;
cout<<"数组所有元素的总和: "<<accumulate(array, array + l, 0)<<endl;
cout<<"数组中最大值的元素: "<<*max_element(array, array + l)<<endl;
cout<<"数组中具有最小值的元素: "<<*min_element(array, array + l)<<endl;
return 0;
}输出结果
数组的元素是: 65 7 12 90 31 113 数组所有元素的总和: 318 数组中最大值的元素: 113 数组中具有最小值的元素: 7
对向量执行操作的程序-
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
vector<int> vec= {65, 7,12, 90, 31, 113 };
cout<<"向量的所有元素之和: "<<accumulate(vec.begin(), vec.end() + 1, 0)<<endl;
cout<<"向量中最大值的元素: "<<*max_element(vec.begin(), vec.end())<<endl;
cout<<"向量中最小值的元素: "<<*min_element(vec.begin(), vec.end())<<endl;
return 0;
}输出结果
向量的所有元素之和: 318 向量中最大值的元素: 113 向量中最小值的元素: 7
排序数组/向量的元素-
在STL中,有一个函数sort()可用于对数组/向量的元素进行排序。该函数使用快速排序技术对数组/向量进行排序。
语法
sort(startIndex, endIndex)
程序对数组的元素进行排序-
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
int array[] = {65, 7,12, 90, 31, 113 };
int l = sizeof(array) / sizeof(array[0]);
cout<<"数组的元素是: ";
for(int i = 0; i<l; i++)
cout<<array[i]<<"\t";
cout<<endl;
cout<<"\nSorting elements of the array…\n\n";
sort(array, array+l);
cout<<"排序后的数组是: ";
for(int i = 0; i<l; i++)
cout<<array[i]<<"\t";
cout<<endl;
return 0;
}输出结果
数组的元素是: 65 7 12 90 31 113 Sorting elements of the array... 排序后的数组是: 7 12 31 65 90 113
程序对向量的元素进行排序-
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
vector<int> vec = {65, 7,12, 90, 31, 113 };
cout<<"向量的元素是: ";
for(int i = 0; i<vec.size(); i++)
cout<<vec[i]<<"\t";
cout<<endl;
cout<<"\nSorting elements of the vector...\n\n";
sort(vec.begin(), vec.end());
cout<<"排序的向量是: ";
for(int i = 0; i<vec.size(); i++)
cout<<vec[i]<<"\t";
cout<<endl;
return 0;
}输出结果
向量的元素是: 65 7 12 90 31 113 Sorting elements of the vector... 排序的向量是: 7 12 31 65 90 113
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短