【发布时间】:2014-05-22 14:58:59
【问题描述】:
我有一个包含不同数据类型的结构列表,如图所示。
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 值。请建议我一种在不影响先前排序的情况下实现结构排序的方法。 提前致谢。
【问题讨论】:
-
请注意,如果您需要保留相等元素的顺序,则使用 std::stable_sort 而不是 std::sort
-
当您说按“结构中的字符串值”排序时,是否包括
strVal和strName或只是strVal?