c++ list random access

kamikaze_pilot picture kamikaze_pilot · Apr 24, 2011 · Viewed 13.8k times · Source

Possible Duplicate:
How to get a certain element in a list, given the position?

so in python you can get an element in a list in a random access fashion....

list = [1,12,3]

print(list[1]) 

and it prints 12....

can you do the same thing with c++ list?

I'm talking about this: http://www.cplusplus.com/reference/stl/list/list/

Answer

Mike Bailey picture Mike Bailey · Apr 24, 2011

In C++, the nearest along to what you want would be a vector:

std::vector<int> v;
v.push_back(1);
v.push_back(12);
v.push_back(3);
std::cout << v[1] << std::endl; // prints 12

You can use the iterators provided to traverse the vector, too. But once you modify the vector (insert or erase), it becomes invalid.

The actual List class provided (which is a doubly-linked list), doesn't provide this sort of feature.