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參數,但它看起來不那麼好。會感謝優雅的解決方案。