A Question about std::list

J

JustSomeGuy

Can you access elements of the std::list like they were an array?
eg.
std::list<int> xlist;
int y;
....
y = xlist[10]; // Returns the 10th element of a list.
 
I

Ivan Vecerina

JustSomeGuy said:
Can you access elements of the std::list like they were an array?
eg.
std::list<int> xlist;
int y;
...
y = xlist[10]; // Returns the 10th element of a list.

No. std::vector and std::deque are the only containers that
provide efficient random-access to their contents.
An equivalent function could be implemented, but it will
require linear time ( O(N) to access the Nth element ).

Cheers,
Ivan
 
A

Andrew Koenig

Can you access elements of the std::list like they were an array?

No. If you wanted, you could write your own function to achieve the same
effect, but it's not generally possible to do so efficiently.

What are you trying to do?
 
J

JustSomeGuy

Andrew said:
No. If you wanted, you could write your own function to achieve the same
effect, but it's not generally possible to do so efficiently.

What are you trying to do?

I think the answer I was looking for was to switch to a vector class instead
of the list class.
 
I

Ivan Vecerina

JustSomeGuy said:
I think the answer I was looking for was to switch to a vector class
instead of the list class.

std::vector should be the default-choice container.

However, depending on the operations that you need to perform
(e.g. adding/removing items, FIFO, sorting, etc), another
standard container (std::deque or even std::set) could be
a better choice.
( The information you have provided does not allow for a definite
recommendation, which is why Andrew asked you for more details. )

Regards,
Ivan
 

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

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top