I am working on a circular, doubly-linked list for a class assignment, and I am having some trouble with it. When I try placing my iterator into either my own prefix_sum method or the STL version (partial_sum), it gives an error on the lines *result = val; and *++result = val; (and the equivalent lines of partial_sum), stating that an lvalue is required as left operand of assignment.
The STL version of iterator works fine in my prefix_sum method, so I know it's a problem somewhere in my iterator, but I can't place it.
/**
* @date 24 November, 2013
* @brief Linked List 6
* @file HW7.cpp
*
* @note
* This work is licensed under a Creative Commons Attribution-NonCommercial 3.0
* Unported License.
*
* Permission is granted to copy, distribute, transmit, and/or adapt this software
* for any and all noncommercial purposes.
*
* For details, see:
* https://creativecommons.org/licenses/by-nc/3.0/
*/
#include "s_list.h"
#include <iostream>
#include <sstream>
#include <list>
#include <numeric>
for(int i = 1; i < 10; i++)
{
stlList.push_back(i);
myList.push_back(i);
}
std::cout << "\nOriginal myList:\n";
typename s_list<int>::iterator myIter = myList.begin();
while (myIter != myList.end()){
std::cout << *myIter << " ";
++myIter;
}
std::cout << "\nOriginal stlList:\n";
std::_List_iterator<int> stlIter = stlList.begin();
while (stlIter != stlList.end()){
std::cout << *stlIter << " ";
++stlIter;
}
std::partial_sum(myList.begin(), myList.end(), (myList.begin()));
prefix_sum(myList.begin(), myList.end(), myList.begin());
prefix_sum(stlList.begin(), stlList.end(), stlList.begin());
std::cout << "\nResult after running myList with STL partial_sum() algorithm\n";
myIter = myList.begin();
while(myIter != myList.end()){
std::cout << *myIter << " ";
++myIter;
}
std::cout << "\nResult after running STL list with my prefix_sum() algorithm\n";
stlIter = stlList.begin();
while (stlIter != stlList.end()){
std::cout << *stlIter<< " ";
++stlIter;
}
}
解決
The reason this does not work is that you did not overload the operator correctly: operator * should return a reference to T, like this:
T& operator *() { return cur->val; }
^
|
+-- Return type needs to be a reference type.
Note that since you are defining your own iterator, you should also provide an overload for the infix operator ->. You should also provide a pair of const overloads, so in the end you should have these four operators: