我一整天都试图弄清楚这一点,因为据我所知,我已经在我的重载+和 - 运算符中编写了代码,我需要弄清楚如何重载[]运算符所以当一个值放在它们内部时,它将正确地遍历列表并指向信息,例如.. [5]将它向前移动5,[ - 5将向后移动,任何帮助都会非常感激,就像我说的那样,似乎我几乎已经在我的+和-...中编写了代码
typename doublyLinkedList<T>::iterator doublyLinkedList<T>::iterator::operator+(const int amount) const {
doublyLinkedList<T>::iterator tempClone(*this);
tempClone.pastBoundary=false;
T i;
if(amount < 0)
{
return this->operator-(-amount);
}
for(i=0; i < amount; i++)
{
if(tempClone.current->forward == NULL)
{
tempClone.pastBoundary =true;
}else
{
++tempClone;
}
}
if(tempClone.pastBoundary == true)
{
return *this;
}else
{
return tempClone;
}
}
template <typename T>
typename doublyLinkedList<T>::iterator doublyLinkedList<T>::iterator::operator-(const int amount) const {
doublyLinkedList<T>::iterator tempClone(*this);
tempClone.pastBoundary=false;
T i;
if(amount < 0)
{
return this->operator+(-amount);
}
for(i=0; i < amount; i++)
{
if(tempClone.current->backward == NULL)
{
tempClone.pastBoundary =true;
}else
{
--tempClone;
}
}
if(tempClone.pastBoundary == true)
{
return *this;
}else
{
return tempClone;
}
}
template <typename T>
T& doublyLinkedList<T>::iterator::operator[](const int index) {
doublyLinkedList<T>::iterator tempClone(*this);
if(index >= 0){
return this->operator+(index);
}else{
return this->operator-(index);
}
答案 0 :(得分:5)
你的operator+
返回一个迭代器,所以operator[]
应该间接返回值:
template <typename T>
T& doublyLinkedList<T>::iterator::operator[](const int index) {
return *(this + index);
}
正如其他地方所述,为非随机访问容器提供operator+
或operator[]
会产生误导,因为O(n)性能可能会令人惊讶。