2012-11-28 158 views
1

可能重複:
Can inner classes access private variables?比較C++和優先級隊列

所以我試圖用一個優先級隊列,並在此隊列的方面,我想定義如果D [i] < D [j],則整數i比另一個整數j「小於」。我怎樣才能做到這一點? (d是一個對象的數據成員)

到目前爲止,我有

/* This function gets the k nearest neighbors for a user in feature 
* space. These neighbors are stored in a priority queue and then 
* transferred to the array N. */ 
void kNN::getNN() { 
    int r; 
    priority_queue<int, vector<int>, CompareDist> NN; 

    /* Initialize priority queue */ 
    for (r = 0; r < k; r++) { 
     NN.push(r); 
    } 

    /* Look at the furthest of the k users. If current user is closer, 
    * replace the furthest with the current user. */ 
    for (r = k; r < NUM_USERS; r++) { 
     if (NN.top() > r) { 
      NN.pop(); 
      NN.push(r); 
     } 
    } 

    /* Transfer neighbors to an array. */ 
    for (r = 0; r < k; r++) { 
     N[r] = NN.top(); 
     NN.pop(); 
    } 
} 

而且在kNN.hh:

class kNN { 

private: 
    struct CompareDist { 
     bool operator()(int u1, int u2) { 
      if (D[u1] < D[u2]) 
       return true; 
      else 
       return false; 
     } 
    }; 
... 

然而,這是給我的錯誤

kNN.hh: In member function ‘bool kNN::CompareDist::operator()(int, int)’: 
kNN.hh:29: error: invalid use of nonstatic data member ‘kNN::D’ 

我該怎麼辦?似乎C++不喜歡它,如果我參考比較器中的特定對象,但我不知道如何解決這個問題,而不用參考D.

謝謝!

+0

這個問題實際上不是關於優先級隊列和比較器,但關於內部類如何訪問包圍類數據成員:HTTP ://stackoverflow.com/questions/486099/can-inner-classes-access-private-variables,http://stackoverflow.com/questions/1604853/nested-class-access-to-enclosing-class-private-data - 成員 – jogojapan

回答

4

您可以傳遞將D對象引用到CompareDist對象的構造函數中,然後使用operator()中的那個D對象。

在本示例中,我存儲了一個指向D的指針。根據D的類型,您可能需要保存D的副本。 (如果D是原始陣列,我的樣品中的語法可以被簡化。)

struct CompareDist { 
    const DType* pD; 
    CompareDist(const DType& D) : pd(&D) {} 
    bool operator()(int u1, int u2) { 
     return (*pD)[u1] < (*pD)[u2]; 
    } 
}; 

priority_queue<int, vector<int>, CompareDist> NN(CompareDist(D)); 
+0

感謝您的解決方案! –

-1

好了,現在我讀過你的問題好,我可以更新的答案:問題是D是包含的kNN實例內的對象,因此它不是static,不能從訪問一個靜態上下文。

您可以通過使用類中的靜態引用d,像

// .h 
class kNN { 
    static Type* current; 
    .. 

    struct CompareDist { 
     bool operator()(int u1, int u2) { 
     if ((*current)[u1] < (*current)[u2]) 
      return true; 
     else 
      return false; 
     } 
    }; 
} 

// .cpp 
Type *kNN::current = NULL; 

void kNN::method() 
{ 
    kNN::current = D; // beforing using the comparator 
    .. 
} 

此外簽名應通過const引用使用元素解決的問題,如

bool operator()(const int &u1, const int &u2) 
+0

對不起,我對此很困惑。我什麼時候提及集合的特定實例?另外爲什麼我需要傳遞一個整數的引用,如果它只是一個整數而不是一個對象? –

+0

我更新了答案以反映您的具體情況,您需要通過引用來避免複製該值。 – Jack

+0

感謝您的幫助! –