2011-04-19 63 views
13

我試圖使用C++標準庫的find算法是這樣的:我使用C++標準庫的find有什麼問題?

template<class T> 
    const unsigned int AdjacencyList<T>::_index_for_node(
     const std::vector<T>& list, const T& node 
) throw(NoSuchNodeException) 
    { 
    std::vector<T>::iterator iter = std::find(list.begin(), list.end(), node); 
    } 

當我嘗試編譯,我得到這些錯誤:

In file included from ../AdjacencyList.cpp:8: 
../AdjacencyList.h: In member function ‘const unsigned int Graph::AdjacencyList<T>::_index_for_node(const std::vector<T, std::allocator<_Tp1> >&, const T&)’: 
../AdjacencyList.h:99: error: expected ‘;’ before ‘iter’ 
../AdjacencyList.h:100: error: ‘iter’ was not declared in this scope 
In file included from ../AdjacencyListTest.cpp:9: 
../AdjacencyList.h: In member function ‘const unsigned int Graph::AdjacencyList<T>::_index_for_node(const std::vector<T, std::allocator<_Tp1> >&, const T&)’: 
../AdjacencyList.h:99: error: expected ‘;’ before ‘iter’ 
../AdjacencyList.h:100: error: ‘iter’ was not declared in this scope 
../AdjacencyList.h: In member function ‘const unsigned int Graph::AdjacencyList<T>::_index_for_node(const std::vector<T, std::allocator<_Tp1> >&, const T&) [with T = int]’: 
../AdjacencyList.h:91: instantiated from ‘const std::vector<T, std::allocator<_Tp1> > Graph::AdjacencyList<T>::neighbours(const T&) [with T = int]’ 
../AdjacencyListTest.cpp:18: instantiated from here 
../AdjacencyList.h:99: error: dependent-name ‘std::vector::iterator’ is parsed as a non-type, but instantiation yields a type 
../AdjacencyList.h:99: note: say ‘typename std::vector::iterator’ if a type is meant 

我覺得像「從屬名稱'std :: vector :: iterator'被解析爲非類型,但實例化產生一個類型「位持有理解我做錯了什麼的關鍵,但是我的豌豆腦不能提取意義。

更新:我需要添加一個typename,按照公認的答案,並且還使用了const_iterator,所以有問題的代碼行變成了:

typename std::vector<T>::const_iterator iter = std::find(list.begin(), list.end(), node); 
+0

STL中沒有'std :: find'。 'std'命名空間表示使用C++標準庫。同時,取消使用'std :: find'會縮小問題的範圍;在這種情況下,你有一個獨立的名字。 – 2011-04-19 16:54:55

+5

其中最後一行錯誤消息包含最有用信息的罕見情況之一... – sth 2011-04-19 16:55:49

+6

來自C++編譯器的錯誤消息實際上包含有用的可操作建議的罕見情況之一。 ;-) – 2011-04-19 16:56:54

回答

31
std::vector<T>::iterator iter = /* .... */; 

iterator是一個從屬名稱(實際上,其取決於在類型參數T上)。相關名被假定除非你使用typename未命名類型:

typename std::vector<T>::iterator iter = /* .... */; 

欲瞭解更多,可以閱讀堆棧溢出的C++ FAQ條目"Where and why do I have to put 「template」 and 「typename」 on dependent names?"

您還需要使用const_iterator,因爲list是const限定。你也許應該放棄異常規範;最好是"never write an exception specification."

+0

非常棒的回答,詹姆斯!實際上,它只是代碼審查而不是答案,但代碼審查總是受歡迎的。 :) – 2011-04-19 17:10:38