代码之家  ›  专栏  ›  技术社区  ›  ravenspoint

std::对共享指针的向量进行排序[关闭]

c++
  •  -1
  • ravenspoint  · 技术社区  · 5 年前

    我有一个cBin类,它的构造函数分配了一个唯一的id。

    我有一个指向垃圾箱的共享指针向量。

    typedef std::shared_ptr< cBin > bin_t;
    

    我有一个cPackEngine类,它的属性是指向bin的共享指针的向量,还有一个返回对向量的引用的方法

    std::vector< bin_t > & bins()
    {
        return myBin;
    }
    ...
    std::vector< bin_t > myBin;
    

    std::sort 在向量中排列容器的顺序

    void SortBinsIntoIncreasingSize( cPackEngine& e )
    {
    
        sort( e.bins().begin(), e.bins().end(),
              []( bin_t a, bin_t b )
        {
            ...
    

    这通常很有效。但有时,对于某些输入,应用程序会在排序中崩溃。

    调试器显示,当lambda函数在处理指向 箱子。所以我补充道:

    sort( e.bins().begin(), e.bins().end(),
          []( bin_t a, bin_t b )
    {
        std::cout << "compare\n" << a->text() << b->text();
        if( a->progID() == b->progID() ) {
            std::cout << "!!!\n" << a->text() << b->text();
            std::cout << " a points to " << a.get() << " has use count " << a.use_count() << "\n";
            std::cout << " b points to " << b.get() << " has use count " << b.use_count() << "\n";
            throw std::runtime_error( "SortBinsIntoIncreasingSize");
        }
    

    compare
    CENPLY6_GREY_GREY  95 5760x180 at 5760 12020
    CENPLY6_GREY_GREY  65 3760x440 at 19760 11760
    compare
    CENPLY6_GREY_GREY  95 5760x180 at 5760 12020
    CENPLY6_GREY_GREY  93 5760x180 at 0 12020
    compare
    CENPLY6_GREY_GREY  95 5760x180 at 5760 12020
    CENPLY6_GREY_GREY  95 5760x180 at 5760 12020
    !!!
    CENPLY6_GREY_GREY  95 5760x180 at 5760 12020
    CENPLY6_GREY_GREY  95 5760x180 at 5760 12020
     a points to 0x2a30740 has use count 3
     b points to 0x2a30740 has use count 3
    terminate called after throwing an instance of 'std::runtime_error'
      what():  SortBinsIntoIncreasingSize
    

    95是发生车祸的垃圾箱的ID。我通过在调用sort之前转储向量来检查向量中是否只有一个bin 95

    for( auto it = e.bins().begin(); it != e.bins().end(); it++ )
        std::cout << (*it)->text();
    

    注意:将真正的whan a和b点返回到同一个对象仍然会崩溃:

        sort( e.bins().begin(), e.bins().end(),
              []( bin_t a, bin_t b )
        {
            std::cout << "compare\n" << a->text() << b->text();
            if( a->progID() == b->progID() ) {
    //            std::cout << "!!!\n" << a->text() << b->text();
    //            std::cout << " a points to " << a.get() << " has use count " << a.use_count() << "\n";
    //            std::cout << " b points to " << b.get() << " has use count " << b.use_count() << "\n";
    //            throw std::runtime_error( "SortBinsIntoIncreasingSize");
    
                return true;
    
    1 回复  |  直到 5 年前
        1
  •  2
  •   Nicol Bolas    5 年前

    处理指向同一个箱子的a和b

    std::sort 不会 将一个对象与它自身进行比较。因此,比较函数需要返回“两个”对象是相同的。


            return true;
    

    标准::排序 要求比较函子提供 . 如果同一对象与 true 对自己来说,那不是 strict ordering sort 因此会导致运行时崩溃。