2012-03-14 3 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 속성을 통해 반복하여 임시 벡터 안에 저장해야합니까? 이 작업을 수행하는 더 쉬운 방법이 있습니까?

고양이를 정렬 할 수 있도록 고양이에 operator<를 구현해야
+0

std :: sort] (http://msdn.microsoft.com/en-us/library/ecdecxh1 (v = vs80) .aspx) 당신은'cat'을 어떻게 정렬하는지에 대한 술어를 사용하기를 원할 것입니다 사물. –

답변

11

:

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 당신은'연산자'를 자유 함수로 정의하거나'std :: sort'에 대한 세 번째 인자로 커스텀 비교 함수를 제공 할 수 있습니다. – mfontanini

+0

왜'std :: sort (cats_copy.begin(), cats_copy.end());'연령 순으로 정렬해야합니까? 모피의 길이 또는 고양이의 이름은 알파벳 순서로 어떻습니까? – Jonny

관련 문제