Random Access Empty STL List

I wanna have random access to a position n in an empty STL list. If the list was not empty, I would easily access it by using advance or just using a loop to increment the iterator to n position. However, when the list is empty, I am unable to increment the iterator.
I got a message saying: "List interior not incrementable."
Thank you.

//Here is what I did

#include <iostream>
#include <list>
using namespace std;

int main()
{
list<int> myList;
list<int>::iterator itr;
itr = myList.begin();
itr++;
myList.insert(itr, 33); //trying to insert 33 in the 2nd position

return 0;
}
Last edited on
Well, the list does not contain the first element, you need to insert the first element first before you can actually insert the second element.

So this one should do what you expect :
1
2
3
4
itr = myList.begin();
myList.insert(itr, 10);
itr++;
myList.insert(itr, 33);
Thank you for your answer.

I know how to populate a STL list. However, the whole point is about an empty STL list.
So, once you insert 10, it is not an empty list anymore.
I wanted to find a way to increment the iterator, to n position, while the STL list is empty.

But, anyway, I appreciate your input.
I wanted to find a way to increment the iterator, to n position, while the STL list is empty.

Iterators iterate over elements contained. You cannot iterate to the nth element if you do not have an nth element.
...specifically, the version of list::insert() you are using inserts a new element before an existing element. An empty list has no existing elements. Hence failure.
You could try using the resize() member function to create a bunch of default entries into your "empty" list.

http://www.cplusplus.com/reference/list/list/resize/

The list would not technically be empty, but the contents could be "empty" values.
Thank you all.
Great inputs.
@Duoas
You can actually insert() in an empty list:

mylist.insert (mylist.end(),10);

It is perfectly legal.


In the example of the op itr is beyond the end().
Topic archived. No new replies allowed.