2012-03-14 7 views
3

可能性の重複によって、オブジェクトのベクトル:
How to use std::sort with a vector of structures and compare function?ソートオブジェクトの属性

私は猫のオブジェクト(何を?)とは明らかに猫のオブジェクトをソートcatSortオブジェクトを持っています。以下はクラスです

class cat { 
public: 
    int age; 
}; 

class catSorter { 
public: 
    vector<cat> cats; 
    vector<cat> SortCatsByAge(); 
    void AddCat(cat new_cat); 
}; 

void catSorter::AddCat(cat new_cat){ 
    this->cats.push_back(new_cat) 
} 

vector<cat> catSorter::SortCatsByAge(){ 
    // Sort cats here by age! 
} 


cat tim; 
tim.age = 10; 

cat mark; 
mark.age = 20 

cat phil; 
phil.age = 3; 

catSorter sorter; 
sorter->AddCat(tim); 
sorter->AddCat(mark); 
sorter->AddCat(phil); 

std::<vector> sortedcats = sorter->SortCatsByAge(); 

私はこれをやり遂げるのが難しいですか?ちょうどcats属性をループして、それらを一時的なベクトルの中に格納して戻すべきですか?これを行う簡単な方法はありますか?猫を並べ替えることができるように

+0

を[ルックアップstd :: sort](http://msdn.microsoft.com/en-us/library/ecdecxh1(v = vs80).aspx)述語を使用して、 'cat'をどのようにソートするかを教えてくださいオブジェクト。 –

答えて

11

あなたは猫のoperator<を実装する必要があります。

class cat { 
public: 
    int age; 
    bool operator< (const cat &other) const { 
     return age < other.age; 
    } 
}; 

をあなたはその後、「アルゴリズム」ヘッダが含まれており、自分のアレイでstd::sortを使用することができます。

vector<cat> catSorter::SortCatsByAge(){ 
    vector<cat> cats_copy = cats; 
    std::sort(cats_copy.begin(), cats_copy.end()); 
    return cats_copy; 
} 
+1

'cat'クラスにアクセスできない場合や、別の目的で異なるプロパティでソートしたい場合はどうすればいいですか? –

+0

@DrewNoakesでは、 'operator <'を空き関数として定義したり、カスタム比較関数を 'std :: sort'の3番目の引数として提供することができます。 – mfontanini

+0

'std :: sort(cats_copy.begin()、cats_copy.end());'年齢順にソートする必要があるのはなぜですか?ファーの長さや猫の名前はアルファベット順にどうですか? – Jonny