How do you get a certain element like "5" of a list?

I can't find anything about getting a certain element of a list. I have a get_elem() function that takes in an int, meaning if the int was "5" I want to return whatever is in the "5" element. I figure I have to use an iterator because that's just how lists work, but I can't find anything other than maybe using distance()

This iwll do it.

1
2
3
4
5
6
7
8
...
int i=0;
while (i<theOneYouWant)
{
  thatIterator++;
  i++;
}
return *thatIterator;

Last edited on
The function is called advance:

1
2
3
  auto it=list.begin();
  advance(it,4);
  cout << *it << endl; //prints the 5th element 


But you should be aware that this has linear complexity for lists.

http://www.cplusplus.com/reference/std/iterator/advance/
Thanks to both of you!
Topic archived. No new replies allowed.