簡體   English   中英

我使用C ++標准庫的查找有什么問題?

[英]What is wrong with my usage of C++ standard library's 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'被解析為非類型,但是實例化產生了一種類型”bit是理解我做錯了什么的關鍵,但我的豌豆腦不能提取意義。

更新:我需要根據接受的答案添加一個typename ,並使用const_iterator ,因此有問題的代碼行變為:

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

iterator是一個依賴名稱(實際上,它取決於類型參數T )。 除非使用typename否則假定從屬名稱不是名稱類型:

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

有關更多信息,請參閱Stack Overflow C ++ FAQ條目“在哪里以及為什么必須在依賴名稱上放置”template“和”typename“?

您還需要使用const_iterator ,因為list是const限定的。 您也應該刪除異常規范; 最好“永遠不要編寫異常規范”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM