operator [] list cpp

Pra*_*iki 0 c++ list

我的列表类使用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;
}
};
Run Code Online (Sandbox Code Playgroud)

在头类中定义.

wil*_*ilx 7

不提供的原因std::list<T>::operator[]是它不具有O(1)复杂性而是O(N).如果您使用的是链接列表,则应该以不涉及索引访问的方式构建算法.

我建议listadv像你在OP中提出的那样反对这个班级.