首先需要明确一点就是 vcetor 容器里的最后一个值是 end() ,即你将 0 ~ 9 十个数依次压进 vector ,容器中的最后一个值不是 9,而是 end(); 但是容器的大小还是10.
对 vector 使用 sort 函数,可分为三种情况:
#include<algorithm> 该头文件必必不可少
1、基本类型,vector中的元素类型是统一的,如vector<int> ; vector<double> ; vector<string>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
vector<int> vec;
int n = 4;
while (n--){
int num;
cin >> num;
vec.push_back(num);
}
cout << " prev(vec.end)" << *prev(vec.end()) << endl;
sort(vec.begin(), vec.end());
for (vector<int>::iterator ite = a.begin(); ite != a.end(); ite++){
cout << *ite << endl;
}
return 0;
}
2、vector 中的元素累型有自己定义的结构体或者类,类型不统一;想通过其中一个类型的元素进行比较排序。
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
struct student {
string name;
double score;
};
bool comp(const student &a, const student &b) {
return a.score < b.score;
}
int main() {
vector<student> vec;
int n = 3;
while (n--) {
student stu;
cout << "输入名字:" << '\t';
string name;
cin >> name;
stu.name = name;
cout << endl;
cout << "输入成绩:" << '\t';
double score;
cin >> score;
stu.score = score;
cout << endl;
vec.push_back(stu);
}
cout << "排序前:" << endl;
for (unsigned i = 0; i < vec.size(); i++) {
cout << vec[i].name << '\t' << vec[i].score << endl;
}
sort(vec.begin(), vec.end(), comp);
cout << "排序后:" << endl;
for (unsigned i = 0; i < vec.size(); i++) {
cout << vec[i].name << '\t' << vec[i].score << endl;
}
return 0;
}
3、第二种情况的延申,也就是在比较数相同的情况下,有第二种比较方式;比如成绩相同时,学号小的放在前面。
只需要修改 comp 函数;
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
struct student {
int num;
string name;
double score;
};
bool comp(const student &a, const student &b) {
if (a.score < b.score) {
return true;
}
else if(a.score == b.score && a.num < b.num){
return true;
}
else {
return false;
}
}
int main() {
vector<student> vec;
int n = 3;
while (n--) {
student stu;
cout << "输入学号:" << '\t';
int num;
cin >> num;
stu.num = num;
cout << endl;
cout << "输入名字:" << '\t';
string name;
cin >> name;
stu.name = name;
cout << endl;
cout << "输入成绩:" << '\t';
double score;
cin >> score;
stu.score = score;
cout << endl;
vec.push_back(stu);
}
cout << "排序前:" << endl;
for (unsigned i = 0; i < vec.size(); i++) {
cout << vec[i].name << '\t' << vec[i].score << endl;
}
sort(vec.begin(), vec.end(), comp);
cout << "排序后:" << endl;
for (unsigned i = 0; i < vec.size(); i++) {
cout << vec[i].name << '\t' << vec[i].score << endl;
}
return 0;
}
注意一下,修改 comp函数时需要注意逻辑的完整性,也就是说一定要返回一个值,所以 else {return false} 不可以少了。