std :: list的重载括号运算符

时间:2016-11-24 21:41:51

标签: c++

我想知道如何创建一个重载的括号运算符,它将在std :: list中提供元素的位置。

我班上的列表声明如下:

std::list<Stimulation*>::operator[](const int); 

重载的括号运算符声明是:

std::list<Stimulation*>::operator[](const int position)
{
  auto i = configuration.begin();
  return i + position;

  ***OR***

  std::list<Stimulation*>::iterator i = configuration.begin();
  return i + position;
}

我认为括号运算符的定义如下:

{{1}}

我是这个概念的新手,所以任何帮助都会以正确的方式得到理解。我需要在这种情况下专门使用列表,因为我知道其他容器包括括号运算符作为库的一部分。再次感谢您的耐心和时间。

1 个答案:

答案 0 :(得分:4)

std::list元素在内存中不是连续的,与std::vector元素不同,这就是为什么没有[]运算符存在的原因,因为它效率低,而且这不是列表的原因。

但是,作为练习,您可以使用for循环来实现它。这是我的天真实现,缺少const版本,并且在超出界限时失败了:

#include <list>
#include <iostream>
#include <cassert>

using namespace std;

class MyList : public list<int>
{
public:

    int &operator[](int pos)
    {
       int count=0;
       for (auto &it : *this)
       {
          if (count==pos) { return it;}
          count++;
       }
     assert(false);
   }
};


int main()
{
    MyList l;
    l.push_back(1);
    l.push_back(2);
    l.push_back(3);
    l.push_back(4);
    cout << l[2] << endl;
    return 0;
}

如果元素位于列表末尾(O(N)),则访问时间非常糟糕,因为您无法向list::begin()添加位置。

我想你可以“缓存”最后一次询问的偏移量&amp;迭代器所以如果调用者要求偏移量+ 1(这在程序中很常见),你可以在不从头开始恢复的情况下前进。

注意:刚看到有关std::advance的评论。那里没用(不知道)。