使用C++ STL操作数组和向量
数组和向量是竞赛编程中非常重要的数据结构,用于解决问题。C++编程中的STL(标准模板库)提供了一些函数来执行数组和向量的操作。
让我们看看其中一些函数的实际应用:
查找数组/向量的和、最小值和最大值 - STL 中有一些函数可以帮助你查找数组/向量的和、最大值和最小值。函数及其功能如下:
查找和
accumulate(startIndex, endIndex, initialSum)
数组/向量的最大元素
*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<<"The elments of the array are : "; for(int i = 0; i<l; i++) cout<<array[i]<<"\t"; cout<<endl; cout<<"The sum of all elements of the array: "<<accumulate(array, array + l, 0)<<endl; cout<<"The element with maximum value in array: "<<*max_element(array, array + l)<<endl; cout<<"The element with minimum value in array: "<<*min_element(array, array + l)<<endl; return 0; }
输出
The elments of the array are : 65 7 12 90 31 113 The sum of all elements of the array: 318 The element with maximum value in array: 113 The element with minimum value in array: 7
对向量执行操作的程序:
示例
#include <bits/stdc++.h> using namespace std; int main(){ vector<int> vec= {65, 7,12, 90, 31, 113 }; cout<<"The sum of all elments of the vector: "<<accumulate(vec.begin(), vec.end() + 1, 0)<<endl; cout<<"The element with maximum value in vector: "<<*max_element(vec.begin(), vec.end())<<endl; cout<<"The element with minimum value in vector: "<<*min_element(vec.begin(), vec.end())<<endl; return 0; }
输出
The sum of all elments of the vector: 318 The element with maximum value in vector: 113 The element with minimum value in vector: 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<<"The elments of the array are : "; 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<<"The sorted array is : "; for(int i = 0; i<l; i++) cout<<array[i]<<"\t"; cout<<endl; return 0; }
输出
The elments of the array are : 65 7 12 90 31 113 Sorting elements of the array... The sorted array is : 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<<"The elments of the vector are : "; 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<<"The sorted vector is : "; for(int i = 0; i<vec.size(); i++) cout<<vec[i]<<"\t"; cout<<endl; return 0; }
输出
The elments of the vector are : 65 7 12 90 31 113 Sorting elements of the vector... The sorted vector is : 7 12 31 65 90 113
广告