【问题标题】:Sort a list of structures twice C++对结构列表进行两次排序 C++
【发布时间】: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
  • 当您说按“结构中的字符串值”排序时,是否包括strValstrName 或只是strVal

标签: c++ algorithm sorting


【解决方案1】:

只需一次根据这两个标准进行排序。您可以通过实现字典顺序比较来实现这一点,首先使用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::sortstd::stable_sort 之类的排序算法一起使用时,这将导致首先基于nVal,然后是strVal,然后是strName 进行排序。使用std::tie只是简化字典比较实现的一种手段,但您可以手动完成(这既繁琐又容易出错。)

注意如果您想根据比较标准保持元素的原始顺序被认为是等效的,请使用std::stable_sort。否则,请使用std::sort

【讨论】:

  • @KonradRudolph 我添加了指向sortstable_sort 的链接。我试图弄清楚 OP 到底需要什么。
  • (现在可能还值得一提的是,stable_sort 不需要您编写比较函数。)
  • @KonradRudolph 我一定遗漏了一些明显的东西,或者以不同的方式阅读问题,因为我不明白这一点。
【解决方案2】:

您想先按nVal 排序,但如果元素具有相同的nVal,则按字符串排序。

支持 pre-C++11 编译器的 juanchopanza 回答的一个简单易懂的替代方案是:

bool sortList(const sample& a, const sample& b) // comparison function
{
    if (a.nVal == b.nVal)
    {
        if (a.strVal == b.a.strVal)
        {
            return a.strName < b.strName;
        }
        else
        {
            return a.strVal < b.strVal;
        }
    }
    else
    {
        return a.nVal < b.nVal;
    }
}

【讨论】:

    猜你喜欢
    • 2013-09-16
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多