[英]operator [] list cpp
我的清單類別正在使用operator []。我可以使用這個覆寫類別。 如果有任何理由不提供operator []作為列表,請解釋。 如果下面的代碼有任何錯誤,請清除它。
template<class _Ty,class _Ax = std::allocator<_Ty>> class listadv : public
std::list<_Ty,_Ax>
{
// should declare in top of the class
public:
_Ty operator[](int index)
{
std::list<_Ty,_Ax>::iterator iter = this->begin();
std::advance(iter, index);
return *iter;
}
};
在標頭類中定義。
不提供std::list<T>::operator[]
是它不會具有O(1)復雜性,而不會具有O(N)。 如果使用鏈接列表,則應以不涉及索引訪問的方式來構造算法。
我建議您像在OP中建議的那樣反對listadv
類。
如果您確實想要這樣的訪問,請將其實現為模板函數(例如get_nth
)。
另外,您的operator[]
。 您應該始終提供兩個變體,一個非常量變量返回一個非常量引用,另一個常量變量返回一個const引用。 您永遠不要按值返回元素,因為這會使表達式a[i] = 5
發生非常微妙的失敗(即沒有編譯器錯誤)。
我認為此C ++ 11代碼應能按預期工作:
template <typename Container>
auto get_nth(Container& c, std::size_t n) -> decltype(*c.begin())
{
auto iter = c.begin();
std::advance(iter, n);
return *iter;
}
// ...
std::list<int> l;
// ...
get_nth(l, 3) = 1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.