2013-09-25 44 views
0

我的列表类正在使用operator []。我可以使用这个重写类。如果有任何理由不提供运营商[]的名单,请解释。如果在下面的代码中有任何错误,请清除它。operator [] list cpp

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; 
} 
}; 

定义在标头类中。

+7

从一个标准集装箱公有继承从来都不是一件好事。 –

回答

7

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

我建议不要像你在OP中提出的listadv类。

1

如果您确实想要这样访问,请将其实施为模板化功能(如get_nth)。

此外,您的operator[]。你应该总是提供两个变体,一个是非const的,一个是返回一个非const引用,一个是const变量,返回一个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;