【C++FAQ】怎么给结构体排序
使用stl中的sort,并重载要排序的结构体或类的<号即可。示例代码如下(pku1007题)
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <map> #include <cmath> using namespace std; //只有ACGT这几个数 class DNAStr { public: bool operator < (const DNAStr& other) const{ if (inversions < other.inversions) { return true; } if (inversions > other.inversions) { return false; } return _idx < other._idx; } DNAStr(string str,int idx) { _str = str; _idx = idx; int len = str.size(); inversions = 0; char DNAChars[] = {'A','C','G','T'}; for (int k = 0;k<4;k++) { int nLargerNum = 0; for (int i = 0;i<len;i++) { if (str[i] > DNAChars[k]) { nLargerNum ++; }else if (str[i] == DNAChars[k]) { inversions += nLargerNum; } } } } string _str; int _idx; int inversions; // 逆对数的对数 }; int main() { vector<DNAStr> dnaStrs; int n,m; cin >> n >> m; for (int i = 0;i<m;i++) { string str; cin >> str; DNAStr dnaStr(str,i); dnaStrs.push_back(dnaStr); } sort(dnaStrs.begin(),dnaStrs.end()); for (int i = 0;i<m;i++) { cout << dnaStrs[i]._str << endl; } return 0; }
posted on 2011-06-24 17:25 speedmancs 阅读(554) 评论(0) 编辑 收藏 举报