【问题标题】:How to use existing integer sort to sort integer tuples?如何使用现有的整数排序对整数元组进行排序?
【发布时间】:2011-08-25 03:51:04
【问题描述】:

有谁知道使用现有整数排序(例如 STL 排序)对整数元组进行排序而不修改现有整数排序的有效算法。例如。我想对 4 个整数元组的列表进行排序。元组的格式为:<int,int,int, int>。再次假设整数排序只能处理单个整数。

【问题讨论】:

  • 您是要对每个元素都是一个元组的容器进行排序,还是要对单个元组进行排序??
  • 假设您要对列表进行排序,首先是 还是 ?

标签: c++ algorithm sorting quicksort


【解决方案1】:

您可以使用现有的 C++ 排序例程“排序”对您想要的任何内容进行排序,只需定义您自己的比较函数,例如在您的情况下

sort(mytuplearray, mytuplearray + N, mycomp)

mycomp 在哪里

bool mycomp(tuple& a, tuple& b)
{
     //compare however you like
}

【讨论】:

  • 您甚至可以对元组使用默认值,这是一种按字典顺序进行的比较,在这种情况下,这很可能是人们想要的。
  • 我认为您希望 const tuple& 用于 mycomp 参数。
【解决方案2】:

如果您想使用标量比较器创建字典元组比较器,只需比较最后一对不相等的组件即可。像这样的:

template<typename T>
class LexicographicCompare
{
private:

    T Compare;

public:

    LexicographicCompare(T Compare) : Compare(Compare)
    {
    }

    bool operator()
        ( const tuple<int, int, int> & a
        , const tuple<int, int, int> & b
        ) const
    {
        if (a[0] != b[0])
            return Compare(a[0], b[0]);
        if (a[1] != b[1])
            return Compare(a[1], b[1]);
        return Compare(a[2], b[2]);
    }
};

sort(tuples.begin(), tuples.end(), LexicographicCompare(IntCompare()));

【讨论】:

  • operator&lt; 重载了元组来做这件事。
  • 我没有使用 boost::Tuple,所以不确定他们是否可以为他们的元素使用比较函数。毕竟,Arya 想要重用任意整数比较(据我所知)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多