我有一个结构列表,其中显示了不同的数据类型.
struct sample
{
int nVal;
string strVal;
string strName;
};
Run Code Online (Sandbox Code Playgroud)
现在我按照nVal对该列表进行排序
bool sortList(const sample& a, const sample& b) // comparison function
{
return a.nVal< b.nVal;
}
std::sort(sample.begin(), sample.end(), sortList);
Run Code Online (Sandbox Code Playgroud)
现在我的要求是根据结构中的字符串值对相同的列表进行排序,但它不应该影响第一个排序,即关于int值.请建议我一种方法来实现结构的sorthing而不影响以前的排序.提前致谢.
只需按照两个标准进行排序即可.你可以通过实现字典比较来实现这一点,nVal首先使用,然后使用strVal,和strName:
#include <tuple> // std::tie
bool sortList(const sample& a, const sample& b) // comparison function
{
return std::tie(a.nVal, a.strVal, a.strName) <
std::tie(b.nVal, b.strVal, b.strName);
}
Run Code Online (Sandbox Code Playgroud)
当与排序算法(如std::sortor)一起使用时std::stable_sort,这将导致基于nValfirst 的排序strVal,然后是strName.使用std::tie只是简化字典比较实现的一种方法,但你可以手工完成(这既繁琐又容易出错.)
注意如果要根据比较条件维护被认为等效的元素的原始排序,请使用std::stable_sort.否则,请使用std::sort.
| 归档时间: |
|
| 查看次数: |
450 次 |
| 最近记录: |