operator [] list cpp

时间:2013-09-25 08:01:02

标签: 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;
}
};

在标题类中定义。

2 个答案:

答案 0 :(得分:7)

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

我建议你反对listadv类,就像你在OP中提出的那样。

答案 1 :(得分: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;