c++对于vector等类型的数据处理,经常会涉及到排序,顺序,逆序,或者根据某一个每一个条件排序.今天来捋一捋
==> 实际上发现已经有英文的整理版本,附上链接
1.实现vector元素的顺序排列
// C++ program to sort a vector in non-decreasing
// order.
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
sort(v.begin(), v.end());
cout << "Sorted \n";
for (auto x : v)
cout << x << " ";
return 0;
}
2. 实现vector元素的逆序排列
// C++ program to sort a vector in non-increasing
// order.
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
sort(v.begin(), v.end(), greater<int>());
cout << "Sorted \n";
for (auto x : v)
cout << x << " ";
return 0;
}
template <class T> struct greater : binary_function <T,T,bool> {
bool operator() (const T& x, const T& y) const {return x>y;}
};
其实,这就是一个标准库自带的函数模板,如果我们用less<int>作为第三个参数,那么就是顺序排列
3. 按照某一属性排列
对于一个对象,我们希望按照它的某一个属性进行排列,那要怎么实现呢?
其实根据第二个例子,就知道原理就是定义一个bool函数,设定比较的规则
"比较函数"的关键:
形参: 要比较的对象
返回值: bool
规则:
less==>true :ascending 升序排列
greater==>true: descending 降序排列
下面的代码: 我们要排列car这个对象,其中根据它的属性 position
struct也可以设置constuctor哦
/*************************************************************************
> File Name: struct_sort.cpp
> Author:
> Mail:
> Created Time: So 25 Jul 2021 20:31:53 CEST
************************************************************************/
#include <algorithm>
#include <vector>
#include<iostream>
using namespace std;
struct car{
double speed;
double position;
car(double speed, double position):speed(speed),position(position)
{
speed = speed;
position = position;
}
};
bool comparecar(car& car1,car& car2)
{
return (car1.position<car2.position);//less =>ascending
}
int main()
{
vector<car> fleet{{1,3},{4,2},{3,5},{6,7},{2,9}};
sort(fleet.begin(),fleet.end(),comparecar);
for (auto x:fleet)
{
cout<<x.position<<" "<<x.speed<<endl;
}
}
4. 反向遍历
用迭代器,我们也可以实现对于vector的反向遍历,比如
这就可以用rbegin和rend实现元素的反向遍历
5. 求最值
我们想求一个vector中的最大最小值, c++也提供了对应的函数
/*************************************************************************
> File Name: getVecMin.cpp
> Author:
> Mail:
> Created Time: Mo 26 Jul 2021 08:43:02 CEST
************************************************************************/
#include <vector>
#include <algorithm>
#include<iostream>
using namespace std;
int main()
{
vector<int> array ={1,5,4,5,6,3,22,99};
cout<<"Max "<<*max_element(array.begin(),array.end())<<endl;
cout<<"Min "<<*min_element(array.begin(),array.end())<<endl;
}