我想知道如何创建一个重载的括号运算符,该运算符将在std :: list中提供元素的位置。
我班上的名单宣告如下:
std::list<Stimulation*> configuration;
重载的括号运算符声明为:
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;
}
我是这个概念的新手,因此以适当的方式来帮助您将不胜感激。在这种情况下,我需要专门使用一个列表,因为我知道其他容器包括方括号运算符作为库的一部分。再次感谢您的耐心和时间。
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;
}
如果element在列表(O(N)
)的末尾,则访问时间非常糟糕,因为您无法在上添加位置list::begin()
。
我想您可以“缓存”最后一个询问的偏移量和迭代器,因此,如果调用方要求偏移量+1(在程序中很常见),则可以直接进行操作而无需从头开始。
注意:刚刚看到有关的评论std::advance
。在那里不使用(不知道)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句