std::list - access at index?

G

Gernot Frisch

Hi,

how can I access the nth element in a std::list?? Or should I use a
deque/queue instead?

Thank you,
--
-Gernot
int main(int argc, char** argv) {printf
("%silto%c%cf%cgl%ssic%ccom%c", "ma", 58, 'g', 64, "ba", 46, 10);}

________________________________________
Looking for a good game? Do it yourself!
GLBasic - you can do
www.GLBasic.com
 
M

Marcin Kalicinski

Hi,

You cannot access list element by index. If you want to do it you have to
use vector or deque. You can only access list elements via iterators, or by
front() and back() members.

Cheers,
Marcin
 
J

John Harrison

Gernot Frisch said:
Hi,

how can I access the nth element in a std::list?? Or should I use a
deque/queue instead?

You can't do it efficiently.

#include <iterator>

list<int> x;
....
list<int>::iterator i = x.begin();
std::advance(i, n);
// now i points to the nth member of the list (counting from zero)

Wrap this up in a function and you'll get the same functionality as the MFC
classes you are porting. I would imagine that MFC was doing something
equally inefficient behind the scenes.

john
 
G

Gernot Frisch

You can't do it efficiently.

Yes, I know.
#include <iterator>

list<int> x;
...
list<int>::iterator i = x.begin();
std::advance(i, n);
// now i points to the nth member of the list (counting from zero)

Ah. "std::advance", that was what I was looking for. I need to use
list, so the pointers to my elements stay after insertion of new
elements, thus I can't use vector. I don't care about speed, since I
only have one function where I have to find an element at given index,
and it's not a very important one.

Thank you very much,
Gernot
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top