【问题标题】:How do I sort a CArray of a user defined type?如何对用户定义类型的 CArray 进行排序?
【发布时间】:2010-09-19 15:48:12
【问题描述】:

在 C++ 中是否有内置的方法来对 CArray 进行排序?

【问题讨论】:

    标签: c++ data-structures mfc sorting


    【解决方案1】:

    std::sort() 应该可以工作:

    CArray<int> arrayOfInts;
    arrayOfInts.Add(7);
    arrayOfInts.Add(114);
    arrayOfInts.Add(3);
    std::sort(arrayOfInts.GetData(), arrayOfInts.GetData()+arrayOfInts.GetSize());
    

    这使用指向数组中第一个元素的指针作为开始迭代器,并将指向最后一个元素的指针作为最后一个迭代器(无论如何都不应该取消引用,所以一切都很好)。如果数组包含更多有趣的数据,您还可以传入自定义谓词:

    struct Foo
    {
      int val;
      double priority;
    };
    
    bool FooPred(const Foo& first, const Foo& second)
    {
       if ( first.val < second.val )
          return true;
       if ( first.val > second.val )
          return false;
       return first.priority < second.priority;
    }
    
    //... 
    
       CArray<Foo> bar;
       std::sort(bar.GetData(), bar.GetData()+bar.GetSize(), FooPred);
    

    哦 - 不要使用CArray

    【讨论】:

    • 只是浏览 MSDN,我看不到 CArray 连续存储数据的任何保证。我希望它确实如此,但是...... std::vector 最初有这个缺陷,并且在发现它时已经更正了标准。
    • 参见此处:msdn.microsoft.com/en-us/library/yzsdcs85(VS.80).aspx(或仅阅读 afxtempl.h 中的源代码)。与其说 MFC 是一个标准,不如说是一组 hack。
    猜你喜欢
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 2016-01-13
    相关资源
    最近更新 更多