2011-04-20 37 views
0

與qsort()一樣,似乎C++ std :: sort()不允許將用戶數據傳遞給排序函數。C++新手:std :: sort:如何將用戶數據傳遞給比較函數?

例如: 像struct A { int version; int index; } array[100]這樣的結構數組必須按順序排序,但使用此數組struct B { int value; } key[100]作爲排序關鍵字。 struct A::index索引數組key

這裏有一個非工作排序功能。它需要有一個指針數組key莫名其妙:

bool comp(struct A *a1, struct A *a2) { 
return key[a1->index].value < key[a2->index].value; 
} 

如何實現,使用C++?如何將非全局用戶數據(如key)傳遞給排序函數?

我試圖傳遞一個對象實例作爲std::sort補償,但似乎只有快速排序() - 類似功能是允許的。

(在GNU C,嵌套比較功能可以被用於使用範圍的變量,但GNU C++不提供嵌套函數)。

回答

7

函子不必是函數;他們可以是物體。

struct Comparator { 
    Comparator(int* key) : key(key) {}; 
    bool operator()(struct A *a1, struct A *a2) { 
     return key[a1->index].value < key[a2->index].value; 
    } 

    int* key; 
}; 

/* ... */ 

std::sort(container.begin(), container.end(), Comparator(<pointer-to-array>)); 
+0

我意識到,與()操作員的類實例的作品,以及。 – 0x6adb015 2011-04-21 15:38:13

2

你可以告訴sort究竟如何通過使用比較函子進行排序。

工作例如:

struct Foo 
{ 
    int a_; 
    std::string b_; 
}; 

Foo make_foo(int a, std::string b) 
{ 
    Foo ret; 
    ret.a_ = a; 
    ret.b_ = b; 
    return ret; 
} 
struct ByName : public std::binary_function<Foo, Foo, bool> 
{ 
    bool operator()(const Foo& lhs, const Foo& rhs) const 
    { 
     return lhs.b_ < rhs.b_; 
    } 
}; 

template<class Stream> Stream& operator<<(Stream& os, const Foo& foo) 
{ 
    os << "[" << foo.a_ << "] = '" << foo.b_ << "'"; 
    return os; 
} 
int main() 
{ 
    vector<Foo> foos; 
    foos.push_back(make_foo(1,"one")); 
    foos.push_back(make_foo(2,"two")); 
    foos.push_back(make_foo(3,"three")); 

    sort(foos.begin(), foos.end(), ByName()); 

    copy(foos.begin(), foos.end(), ostream_iterator<Foo>(cout, "\n")); 

} 

輸出:

[1] = 'one' 
[3] = 'three' 
[2] = 'two' 
相關問題