2011-04-20 57 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'