【问题标题】:Problem with bin sortbin 排序的问题
【发布时间】:2011-02-05 07:00:48
【问题描述】:
  //element of chain.     
    struct studentRecord 
            {
           int score;
           string* name;

           int operator !=(studentRecord x) const
              {return (score != x.score);}
        };


    // binsort,  theChain is a single linked list of students and its element is student Record

         void binSort(chain<studentRecord>& theChain, int range)
            {// Sort by score.

               // initialize the bins
               chain<studentRecord> *bin;
               bin = new chain<studentRecord> [range + 1];

               // distribute student records from theChain to bins
               int numberOfElements = theChain.size();
               for (int i = 1; i <= numberOfElements; i++)
               {
                  studentRecord x = theChain.get(0);
                  theChain.erase(0);
                  bin[x.score].insert(0,x);
               }

               // collect elements from bins
               for (int j = range; j >= 0; j--)
                  while (!bin[j].empty())
                  {
                     studentRecord x = bin[j].get(0);
                     bin[j].erase(0);  ////////// here
                     theChain.insert(0,x);
                  }

               delete [] bin;
            }

chain&lt;studentRecord&gt;是一个单链表;在 bin 排序中, bin 是指向 bin[arrange +1] 的指针,其元素为 chain&lt;studentRecord&gt; 。代码bin[j].erase(i)delete 节点ibin[j].get(i) 将获取节点 i 的元素(即 studentRecord)。代码中while (!bin[j].empty())是用来清空链的,但是bin[j]不能为空,因为它是一个元素数组,对吗?

谢谢。

【问题讨论】:

    标签: c++ algorithm sorting bin


    【解决方案1】:

    是的,垃圾箱确实可以是空的。 empty 的 bin 和 existing 的 bin 之间有一个微妙但重要的区别。您认为 bin 是数组的成员是正确的,因此 存在 位置 i 的 bin 用于数组边界内的任何 i。但是,该垃圾箱不一定必须有任何东西。如果输入列表中没有任何元素碰巧落入该 bin 中,则它可能根本没有任何内容。

    如果您将一排玻璃杯放在桌子上并开始向其中一些玻璃杯灌水,那么这个问题就有一个很好的物理类比。连续的所有玻璃杯都存在并且定义明确,但它们不一定都是空的,尤其是当您开始倒出它们时(就像您在上面的这个 bin 排序示例中所做的那样)。

    【讨论】:

    • 谢谢,我现在明白了。我以为 bin[j] 会存储chainNode,但实际上,它存储了firstNodePointer,它将指向位于堆中的firstNode 的内存。所以即使我使用delete firstNodefirstNodePointer 仍然存在于bin[j]firstNode 的空间是空的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 2013-06-04
    • 1970-01-01
    • 2015-11-22
    • 2017-03-30
    相关资源
    最近更新 更多