我的列表类正在使用运算符[]。我可以使用这个覆盖类吗?如果有任何理由不为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;
}
};
在头类中定义。
最佳答案
不提供的原因std::list<T>::operator[]
是它不会是 O(1) 的复杂度,而是 O(N) 的复杂度。如果您使用链表,您应该以不涉及索引访问的方式构建您的算法。
我建议反对 listadv
像你在 OP 中建议的那样上课。
关于c++ - 运算符 [] 列出 cpp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18999388/