2011-12-02 20 views
0

我想檢查兩個向量是否有任何共同的元素。這個語法有什麼問題?C++將向量傳遞給函數模板

// Check whether the current list and the input l2 share any nodes or not 
bool shared(const VectorList<NODETYPE> &l2); 

template< typename NODETYPE > //SHARED 
bool VectorList< NODETYPE>::shared(const VectorList<NODETYPE> &l2) 
{ 

    for(int i = 0; i < (int)vList.size(); i++) 
     { 
     for (int j = i; j < (int)l2.size() ; j++) 
      { 
        if (vList[i] == l2[j]) 
        { 
         return(1); 
        } 
      } 
     } 

    return(0); 

} 
+3

你可能想發佈爲什麼你認爲你的代碼有問題。如果這是一個編譯器錯誤,編譯器的名稱及其版本也可能有所幫助。 – sbi

+0

總是發佈編譯器錯誤。他們已經完成檢查語法,以便人們不會自己做。 – Beginner

+0

你知道'std :: vector'不是懶惰,你應該使用它以及爲標準模板容器設計的STL算法。 – AJG85

回答

5

假設你已經實現VectorList爲(類似)的標準集裝箱,我會考慮寫(見find_first_of):

template<typename T> 
bool VectorList<T>::shared(const VectorList<T> &l2) const // <-- NOTE added const 
{ 
    return end() != std::find_first_of(
     begin(), end(), 
     l2.begin(), l2.end()); 
} 

注意,(最壞情況下)運行的複雜性仍然會是二次的(或O(n*m)

+0

再次您!再一次+1! – Beginner

2

您的向量?因爲如果沒有,你不應該做J =,否則它不會如果你開始你的第二個for循環其中j找到一些共同的價值觀,即

1 2 3 
2 3 4 

=我,你永遠也找不到了共享值「2」。所以你需要開始你的第二個循環每次從向量的開始(j = 0)