2013-04-04 126 views
1

在本練習中,我應該創建一個由矢量支持的優先級隊列類。這段代碼除了最後的合併功能之外還有效。如何從一個和兩個創建該類的新實例,並返回該類的實例?如何從類中的某個函數返回一個類的實例?

#include "pqueue-vector.h" 
    #define PR(x) cout << #x " = " << x << "\n"; 
    using namespace std; 

    VectorPQueue::VectorPQueue() { 
     Vector<string> pQueue; 
    } 

    VectorPQueue::~VectorPQueue() { 

    } 

    string VectorPQueue::peek() const { 
     if(isEmpty()) { 
      error("peek; Attempting to peek at an empty queue"); 
     } 
     string result = pQueue.get(0); 
     return result; 
    } 

    string VectorPQueue::extractMin() { 
     if (isEmpty()) { 
      error("extractmin; Queue is empty"); 
     } 
     int min = 0; 
     string minimum = pQueue.get(0); 
     for (int i= 1; i < logSize; i++) { 
      string check = pQueue.get(i); 
      if (check < minimum) { 
       min = i; 
       minimum = check; 
      } 
     } 
     pQueue.remove(min); 
     logSize--; 
     return minimum; 
    } 

    void VectorPQueue::enqueue(const string& elem) { 
     pQueue.add(elem); 
     logSize++; 
    } 


    VectorPQueue *VectorPQueue::merge(VectorPQueue *one, VectorPQueue *two) { 

     VectorPQueue result; 
     for (int i = 0; i < one->size(); i++) { 
     string test1 = one->extractMin(); 
     string test2 = two->extractMin(); 

       result.enqueue(test1); 
       result.enqueue(test2); 
      } 
     // placeholder so method compiles.. 
     // replace with your own implementation 
     return new VectorPQueue result; 
    } 

回答

0

我不會爲你解決這個問題,但會給你一個提示。

大綱應該如下:

VectorPQueue *VectorPQueue::merge(VectorPQueue *one, VectorPQueue *two) { 
    VectorPQueue* result = new VectorPQueue; 
    // TODO: populate *result 
    return result; 
} 
+0

啊,也在情理之中非常感謝! – 2013-04-04 12:43:00

+0

@RobbieCooper,爲什麼你不能只是返回一份副本? – Shoe 2013-04-04 12:43:41

+0

我做了什麼NPE建議,工作的一種享受。 – 2013-04-04 15:54:12

相關問題