我有两个载体
vector<string> names={"Raymond","Cynthia","David","William","Mike"}
,然后我正在对每个学生进行get_mark()
来电
vector<int> marks={50,80,45,25,90} .
现在我需要根据学生的标记对两个向量进行排序, 即结果必须是
vector<int> marks_sorted ={25,45,50,80,90}
和
vector<string> names_sorted ={"William","David","Raymond","Cynthia","Mike"}
我能想到的一种方法是首先做一些标记,然后比较排序和未排序的标记向量然后对名称进行排序,但是有一种优雅的方式吗?
- 只需添加一种方法,以便其他人参考
#include "stdafx.h"
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <vector>
using std::vector;
#include <utility>
using std::pair;
#include <algorithm>
using std::sort;
#include <string>
using std::string;
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> data ;
data.push_back(5);
data.push_back(16);
data.push_back(4);
data.push_back(99);
vector<string> names ;
names.push_back("Crystal");
names.push_back("Bob");
names.push_back("Mynah");
names.push_back("TopNerd");
vector<int> index(data.size(), 0);
for (int i = 0 ; i != index.size() ; i++) {
index[i] = i;
}
sort(index.begin(), index.end(),
[&](const int& a, const int& b) {
return (data[a] < data[b]);
}
);
for (int i = 0 ; i != index.size() ; i++) {
cout << index[i] << endl;
}
for (int i = 0 ; i != index.size() ; i++) {
cout << data[index[i]] << endl;
}
for (int i = 0 ; i != index.size() ; i++) {
cout << names[index[i]] << endl;
}
getchar();
return 0;
}
答案 0 :(得分:0)
这样做的优雅方式(我认为)如下
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <vector>
using std::vector;
#include <utility>
using std::pair;
#include <algorithm>
using std::sort;
#include <string>
using std::string;
int main() {
vector<pair<string, int>> vector_of_students
{{"Raymond", 1}, {"Cynthia", 80}, {"David", 85}};
std::sort(vector_of_students.begin(), vector_of_students.end(),
[](const std::pair<string, int>& p1, const std::pair<string, int>& p2) {
return p1.second < p2.second;
});
// print the values out
for (const auto& pa : vector_of_students) {
cout << pa.first << '\t' << pa.second << endl;
}
return 0;
}
这里我使用了自定义比较器的sort方法,问我是否需要帮助理解语法。