2011-11-30 93 views
-1

我想弄清楚在多个条件下对数组进行排序的最佳方法。我想对一个数组进行排序,然后根据第一个条件排序该数组的一个子集。排序分类矢量的子集

例子:

说我们有数据:{ ("cat", 2), ("dog", 4), ("cat", 1), ("dog", 3) }

我们解决这首先根据串的字母顺序:

{ ("cat", 2), ("cat", 1), ("dog", 4), ("dog", 3) }

然后我们两个子集进行排序(集猫和狗的组合):

{ ("cat", 1), ("cat", 2), ("dog", 3), ("dog", 4) }

另外,我使用具有下面的头一个递归快速排序方法:

void quickSort(vector<Type*>, int left, int right) 

其中左和右是边界指数,通过该载体应进行排序。

我应该向排序方法本身添加代码还是应该再次调用排序方法?

+0

你应该自己思考一下。别人的帮助不会帮助你自己解决其他问题。我建议你不要使用StackOverflow来解决你的功课。 – Beginner

+0

这不是一个家庭作业,自学,FYI。我一直在想。我已经知道了,我正在寻找我说的“最好”的方式。我正在寻找现在优化。 – HJM

回答

2

通常,您需要自定义比较器进行排序。

struct Foo { 
    std::string name; 
    int count; 
    struct Less { 
    bool operator()(const Foo &lhs, const Foo &rhs) const { 
     if ((int c = lhs.name.compare(rhs.name)) != 0) 
     return c < 0; 
     return lhs.count < rhs.count; 
    } 
    }; 
}; 

std::vector<Foo> foos; 
// ... 
std::sort(foos.begin(), foos.end(), Foo::Less()); 

如果您不能只使用一个自定义操作符,则可以使用稳定的排序。

正如Mark指出的,std::sort不是稳定排序。相反,您需要使用std::stable_sort

您想按照日益重要的顺序独立对它们进行排序。所以,你按数字排序,然后按字符串排序。

struct Foo { 
    std::string name; 
    int count; 
    struct NameLess { 
    bool operator()(const Foo &lhs, const Foo &rhs) const { 
     return lhs.name.compare(rhs.name) < 0; 
    } 
    }; 
    struct CountLess { 
    bool operator()(const Foo &lhs, const Foo &rhs) const { 
     return lhs.count < rhs.count; 
    } 
    }; 
}; 

std::vector<Foo> foos; 
// ... 
std::stable_sort(foos.begin(), foos.end(), Foo::CountLess()); 
std::stable_sort(foos.begin(), foos.end(), Foo::NameLess()); 

你宁愿先明显,但后者可以派上用场保持组合和/或运行时配置的算法简单。

参考:

cplusplus.com C++ : Reference : STL Algorithms : stable_sort

cplusplus.com C++ : Reference : STL Algorithms : sort

+0

如果你要使用多种排序,你会按照日益重要的顺序排序吗?喜欢:sort(nums);排序(字符串); ...;排序(moreImportantCriteria); ? – HJM

+0

'std :: sort'不稳定,所以如果您使用多种排序方式,那么*无法保证*如果以前的排序对最终结果有任何影响。 –

+0

@霍维是的,那是我试图沟通。这与使用单个比较器版本不同。 –

2

如果您存储数据为vector<pair<string, int> >,那么你可以只使用std::sort(vec.begin(), vec.end());,它只会工作,因为pairoperator<将已经使用对象的两个部分来进行排序。

2

你可以超载<运营商,那么你可以使用vector.unique(),然后vector.sort()

2

你的情况你需要一个自定义的比较器,因为你正在混合数据类型,你不能比较你的标准比较器只能比较相同的数据类型,不知道你的标准会排序。