排序並記錄排序前的索引(類似matlab sort函數)
這裡用到vector比較方便。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct num_label {
int num;
int label;
};
//自定義「大於」
bool comp(const num_label &a, const num_label &b) {
return a.num > b.num;
}
bool comp2(const num_label &a, const num_label &b) {
return a.num < b.num;
}
int main()
{
vector<num_label> vectorNumLabel(5);
vectorNumLabel[0].num = 78 ;
vectorNumLabel[0].label = 0;
vectorNumLabel[1].num = 49;
vectorNumLabel[1].label = 1;
vectorNumLabel[2].num = 300;
vectorNumLabel[2].label = 2;
vectorNumLabel[3].num = 40;
vectorNumLabel[3].label = 3;
vectorNumLabel[4].num = 550;
vectorNumLabel[4].label = 4;
cout << "===========排序前================" << endl;
for (vector<num_label>::iterator it = vectorNumLabel.begin(); it != vectorNumLabel.end(); it++) {
cout << "num: " << it->num << " label: " << it->label << endl;
}
cout << endl;
cout << endl;
cout << endl;
sort(vectorNumLabel.begin(), vectorNumLabel.end(), comp);
cout << "===========排序後,由大到小================" << endl;
for (vector<num_label>::iterator it = vectorNumLabel.begin(); it != vectorNumLabel.end(); it++) {
cout << "num: " << it->num << " label: " << it->label << endl;
}
cout << endl;
cout << endl;
cout << endl;
sort(vectorNumLabel.begin(), vectorNumLabel.end(), comp2);
cout << "===========排序後,由小到大================" << endl;
for (vector<num_label>::iterator it = vectorNumLabel.begin(); it != vectorNumLabel.end(); it++) {
cout << "num: " << it->num << " label: " << it->label << endl;
}
system("pause");
return 0;
}
※Python基礎:計算list中各個元素出現的頻率
※開源庫 lua-cjson 安裝及使用
TAG:程序員小新人學習 |