Reputation: 156
I am currently working on creating a header file that acts like the standard library. I am in the progress of implemeing .end() for my linked list. In my cpp file I have an integer pointer which is expected to recieve the value of the .end() like
int* itrend;
itrend = ca.end();
ca
is just an instance of my object in my header file.
In my hpp file, I have a list iterator going to my listofvalues.end()
. I would like to return the .end()
value like
int* end()
{
std::list<value_type>::iterator i = listOfValues.end();
return (&*i);
}
My "List of values" is just a list holding several ints. eg
[1,2,3,4,5,6,7,8,9]
In my hpp file, I have a list iterator going to my listofvalues.end()
. I would like to return the .end()
value (which returns a list iterator); now this posess a problem that it returns the list iterator when I want to have an integer pointer. I have tried to deference it and take the address by using &*
and this will give an error saying "List Iterator Not Dereferencable". I know it's because I'm trying to get the element after the last value, but that is exactly what I need to return, since I am trying to re-implement the linked list .end()
method.
Does anyone know how I can have an integer pointer point to the List.end()
?
Any assistance is appreciated.
Upvotes: 2
Views: 2023
Reputation: 49976
how do you use your own impementaton of end() anyway? why not returning null when iterator whould return end() ?
int* end()
{
return NULL;
}
Upvotes: 2
Reputation: 16148
The idea of representing the end of the a Linked list with a pointer is somewhat flawed, because you can't progress a pointer with ++ in a linked list, it doesn't iterate through anything.
If you you want to get the back of a list implement l.back()
and return a reference to the last value.
Upvotes: 0
Reputation: 121961
To implement begin()
and end()
in a style similar to STL return iterator
s, not pointers:
template <typename value_type>
class my_list
{
public:
typedef std::list<value_type>::iterator iterator;
typedef std::list<value_type>::const_iterator const_iterator;
iterator begin() { return listofValues.begin(); }
const_iterator begin() const { return listofValues.begin(); }
iterator end() { return listofValues.end(); }
const_iterator end() const { return listofValues.end(); }
};
Upvotes: 4
Reputation: 476980
You cannot. That's why the standard library containers are more general than a flat array. In a C-style array, you can form the pointer one-past-the end (although you are not allowed to dereference it) and use it as a sentinel. In a more abstract container, there is no such "natural" mechanic, which is why iterators were invented in the first place: They are a generalization of pointers that works in more general contexts. Each container's iterator type must solve the problem of providing a suitable "end" sentinel value in its own way.
Upvotes: 2