我有一个具有不同数据类型的结构列表,如图所示。
struct sample
{
int nVal;
string strVal;
string strName;
};
现在根据 nVal 对该列表进行排序,我使用了
bool sortList(const sample& a, const sample& b) // comparison function
{
return a.nVal< b.nVal;
}
std::sort(sample.begin(), sample.end(), sortList);
现在我的要求是根据结构中的字符串值对同一个列表进行排序,但它不应该影响第一个排序,即关于 int 值的排序。请建议我一种在不影响先前排序的情况下实现结构排序的方法。 提前致谢。
最佳答案
只需一次根据这两个标准进行排序。您可以通过实现字典序比较来实现这一点,首先使用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);
}
当与排序算法一起使用时,例如 std::sort
或 std::stable_sort
,这将导致排序首先基于 nVal
,然后是 strVal
,然后是 strName
。 std::tie
的使用只是一种简化字典顺序比较实现的手段,但您可以手动完成(这既乏味又容易出错。)
注意 如果您想保持根据比较标准被视为等效的元素的原始顺序,请使用 std::stable_sort
。否则,使用 std::sort
。
关于c++ - 对结构列表进行两次排序 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23799182/