4

我正在编写一个函数来比较两个列表的内容。元素的顺序无关紧要,所以我在比较之前对它们进行了排序。列表可以是普通类型list<int>,也可以是列表列表list<list<int> >

这是一个完整的精简示例:

#include <list>

template <typename T>
bool lessThanInAnyOrder(T lhs, T rhs)
{
  return lhs < rhs;
}

template <typename T>
bool lessThanInAnyOrder(std::list<T> lhs, std::list<T> rhs)
{
  lhs.sort(lessThanInAnyOrder<T>);
  rhs.sort(lessThanInAnyOrder<T>);

  //Do comparisons here, but for now just:
  return false;
}

int main()
{
  std::list<int> list1;
  std::list<int> list2;
  lessThanInAnyOrder(list1, list2);
}

这在 GCC 4.3.3 中编译,但在 Visual Studio 2008 中,它在我调用的地方给出了以下编译错误lhs.sort()

error C2660: 'std::list<_Ty>::sort' : function does not take 1 arguments

有什么建议么?

4

4 回答 4

3

编译失败,因为编译器无法选择重载的“lessThanInAnyOrder”函数传递给 list::sort。您必须像这里一样明确指定它的类型。

template <typename T>
bool lessThanInAnyOrder(std::list<T> lhs, std::list<T> rhs)
{
  bool (*comparer)(T, T) = &lessThanInAnyOrder<T>;
  lhs.sort(comparer);
  rhs.sort(comparer);
 
  //Do comparisons here, but for now just:
  return false;
}
于 2011-06-30T09:02:08.173 回答
3

首先:我想如果你想比较集合而不考虑它们的顺序,你可能正在寻找std::set,算法set_differenceset_intersectionset_unionset_symmetric_difference

对你的问题

您正在尝试实现按策略排序;如果您不能简单地进行专业化std::less<>为了该确切目的而存在),您可以自己取消自定义策略:(在codepad.org上运行的代码

#include <list>
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>

namespace applogic
{
    template <typename T>
    struct sort_policy
    {
        typedef std::less<T> predicate_t;
    };

    template <> struct sort_policy<std::string>
    {
        struct _Cmp { bool operator()(const std::string& a, const std::string& b) { return a.length()>b.length(); } };
        typedef _Cmp predicate_t;
    };

    template <typename C>
        void sort(C& cont)
    {
        typedef typename sort_policy<typename C::value_type>::predicate_t P;
        std::sort(cont.begin(), cont.end(), P());
    }

    template <typename T>
        void sort(std::list<T>& cont)
    {
        typedef typename sort_policy<T>::predicate_t P;
        cont.sort(P());
    }
}

template <class C>
    static void dump(const C& cont, const std::string& msg="")
{
    std::cout << msg;
    std::copy(cont.begin(), cont.end(), std::ostream_iterator<typename C::value_type>(std::cout, ", "));
    std::cout << std::endl;
}

int main()
{
    using applogic::sort;

    std::vector<int> ints;
    ints.push_back(13);
    ints.push_back(-3);
    ints.push_back(7);

    dump(ints, "before: ");
    sort(ints);
    dump(ints, "after: ");

    std::list<std::string> strings;
    strings.push_back("very very long");
    strings.push_back("tiny");
    strings.push_back("medium size");

    dump(strings, "before: ");
    sort(strings);
    dump(strings, "after: ");

    return 0;
}
于 2011-06-30T09:17:17.193 回答
2

使用显式类型参数包装函数std::ptr_fun

lhs.sort(std::ptr_fun<T, T>(lessThanInAnyOrder<T>));
于 2011-06-30T08:47:02.130 回答
0

我的猜测,对于int类型,您可以简单地这样写:

lhs.sort();
rhs.sort();

演示。

于 2011-06-30T08:40:17.157 回答