C++研究

C++细节深度探索及软件工程

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  37 随笔 :: 0 文章 :: 74 评论 :: 0 Trackbacks
#include <iostream>
#include 
<vector>
#include 
<algorithm>
using namespace std;

struct StructTerm
{
    
int TermID;
    
float Occurency;
}
;

typedef vector
<StructTerm> TERMS;
class Comparer
{
public:

    
bool operator () (const StructTerm & va1, const StructTerm & va2)
    
{
        
return va1.Occurency > va2.Occurency;
    }

}
;
int main()
{
    TERMS terms;
    StructTerm s;
    s.TermID 
= 1;
    s.Occurency 
= 0.8;
    terms.push_back(s);
    s.TermID 
= 2;
    s.Occurency 
= 0.6;
    terms.push_back(s);
    
    s.TermID 
= 2000;
    s.Occurency 
= 0.68;
    terms.push_back(s);
    
    sort(terms.begin(), terms.end(), Comparer());

    
for(int i = 0; i < terms.size(); ++i)
    
{
        cout 
<< terms[i].TermID << "  ";
    }

    cout 
<< endl;
}
posted on 2008-01-15 21:03 常兴龙 阅读(2109) 评论(2)  编辑 收藏 引用 所属分类: STL

评论

# re: 对包含Struct的Vector就其中的一种属性排序 2008-04-24 14:49 ruansun
这样写固然可以,但是如果要对TermID排序,还得写
class Comparer_termid
{
public:

bool operator () (const StructTerm & va1, const StructTerm & va2)
{
return va1.TermID> va2.TermID;
}
};
如果参数列表有100个的话,是不是每一个都需要一个上面的class定义才能排序呢?
怎么写才能更简单呢?  回复  更多评论
  

# re: 对包含Struct的Vector就其中的一种属性排序 2008-08-14 09:32 xx
应该没什么特别简单的办法了吧。这样不挺好吗?我一般都是把Comparer
放到StructTerm里面,用的时候用StructTerm::Comparer

  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


> hi的博客