【问题标题】:C++ STL list operator overloading for pairs (sorting according to first value, accessing with second value)C ++ STL列表运算符重载对(根据第一个值排序,使用第二个值访问)
【发布时间】:2011-04-12 06:50:03
【问题描述】:

您好,我有一些用于 std::list 的重载运算符。

我将对存储在一个列表中,由一个 int 值和一个位置数组组成:

  typedef std::pair< int, std::vector<int,3> > pointPairType;
  typedef std::list< pointPairType > pointListQueueType;
  pointListQueueType pointsQueue;
  // adding some points to the list

我想根据对的第一个值对列表进行排序, 我虽然这会工作:

创建一个比较类,

并用它提供短算法:

// comparison function
template < class T1, class T2 >
class compareFirst
{
  public:
  bool operator() (const std::pair<T1,T2>& l, const std::pair<T1,T2>& r)
    {
    return l.first < r.first;
    }
};

... 主要是:

  // use of sorting algorithm : error here
  pointsQueue.sort(< int, std::vector<int,3> >compareFirst);

但我在'

任何帮助将不胜感激! 谢谢!

【问题讨论】:

    标签: c++ templates list std


    【解决方案1】:

    第一个问题是std::vector&lt;int, 3&gt;没有这样的类型。假设您打算使用 3 元素数组,std::array&lt;int, 3&gt;(或 std::tr1::array 或 boost::array,取决于编译器)是您所需要的,或者只是 std::vector&lt;int&gt;

    其次,那些intstd::vector&lt;int, 3&gt; 是模板参数,它们告诉编译器在许多可能的compileFirst 之间进行选择。他们在他们应用的标识符之后,而不是在它之前。

    以下在 GCC 4.5.2 和 MSVC 2010 上编译和运行:

    #include <list>
    #include <array>
    typedef std::pair< int, std::array<int, 3> > pointPairType;
    typedef std::list< pointPairType > pointListQueueType;
    pointListQueueType pointsQueue;
    template < class T1, class T2 >
    struct compareFirst
    {
        bool operator() (const std::pair<T1,T2>& l, const std::pair<T1,T2>& r) const
        {
            return l.first < r.first;
        }
    };
    int main()
    {
        pointsQueue.sort(compareFirst< int, std::array<int,3> >());
    }
    

    【讨论】:

    • 非常感谢这个非常详细的答案。确实,我写的例子太快了(std::vector 错误)。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 2021-10-12
    • 2013-04-07
    相关资源
    最近更新 更多