2011-10-28 54 views
3

我想和接口的功能是這樣的:查找迭代器的指數在STL容器 - 需要模板函數

template<typename T, typename R> int find_index (const T& list, const R& value); 

據我所知,有在STL返回迭代器find()。我需要返回迭代器的索引(即使對於非索引容器,例如std::list)。我想這樣的代碼:

template<typename T, typename R> 
int find_index (const T& list, const R& value) 
{ 
    int index = 0; 
    for (T::const_iterator it = list.begin(); it != list.end(); it++, index++) 
     if ((*it) == value) 
      return index; 
    return -1; 
} 

但是編譯器顯示了it錯誤 - 好像它是不允許從模板類型名獲得const_iterator。我可以繞過嗎?

在最糟糕的情況下,我可以通過開始和結束迭代器find_index參數,但它看起來不那麼好。會感謝優雅的解決方案。

回答

11
for (typename T::const_iterator it = list.begin(); it != list.end(); ++it, ++index) 

應該解決你的問題。

當使用依賴類型(取決於模板參數類型),編譯器不知道const_iterator是一種類型,直到它用實例化一個具體類型的模板,它也可能只是一個靜態變量或什麼的。使用typename關鍵字,你告訴他const_iterator確實是一種類型。

在C++ 11你也可以使用關鍵字auto規避整個typename問題:

for (auto it = list.begin(); it != list.end(); ++it, ++index) 

如果你已經有了迭代器(也許從一些其他的操作),用戶也可以直接從列表中的計算距離開始這個迭代:

#include <iterator> 

int index = std::distance(list.begin(), it); 

但由於這具有線性複雜的std::list,使用您的自制find_index功能比std::find接着std::distance至少在性能方面更好。