Hi everyone!
How can I index a list with an integer? I canīt add integers to iterators
Thanks any help!
Hi everyone!
How can I index a list with an integer? I canīt add integers to iterators
Thanks any help!
Nothing more to tell about me...
Happy day =)
A linked list?
Linked lists generally don't support random accessing, i.e. indexing, as it's horribly slow. Generally iterators override the increment and de-increment operators (++, --), in order to walk through the list.
If you really needed to, you could overload the arithmetic operators (+, -), with code like this:
With that you could write the operator[] function fairly easily by starting with the beginning element of the list and adding the index. However I don't remember the syntax for that particular operator, so I'll leave that to you or someone else to look up.Code:iterator List::operator+(iterator pos, int index) { for(size_t count = 0; count < index; count++) { pos++ } return pos; }
Last edited by AH_Tze; 05-26-2004 at 05:02 PM.
Why not use a vector instead of a list?
Just Google It. √
(\ /)
( . .)
c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.
I'm going to feel really silly if that was the answer he was looking for. I've been working on implementing a linked-list for the last month in my data structs class, so I just assumed people randomly rewrite basic containers for no reason.
/me heads off for a very long nap
Well, anyways if you do need some list-exclusive functionality, you can do the operator+ overloading if you're indexing only rarely, or you can use a vector and use a STL copy algorithm to transfer the vector to a list, use the list functionality and convert back to vector, if the list functionality is rarely needed (by rarely I mean 'once every half hour or more'). Of course, most of the time option (a) will be the better choice, especially if you have a lot of elements in the container, but if you don't need that list stuff, you might as well use a vector.
Actually, the thought just occurred to me that you might want to use a std::deque, since it's got indexing and still has most of the std::list stuff that you might want.
Just Google It. √
(\ /)
( . .)
c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.
Thanks for the help!
I was thinking in something like:
But I'll use vectors.Code:int returnElement(list<int>& l, int index){ return *(l.begin() + index); }
Nothing more to tell about me...
Happy day =)
>>I'm going to feel really silly if that was the answer he was looking for.
Has it started yet?
Just Google It. √
(\ /)
( . .)
c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.