fragon
fragon

Reputation: 3471

STL List adding and removing chosen element

I'm coding simple program which uses lists. I've already created my list with all of its functions, but now I would like to convert it to STL. I've successfully done it a few of my functions but I'm stuck with a one which should add new element and also remove an element chosen by the user.

Thats my code:

list <Komputer> lista_komputerow_STL;
list <Komputer>::iterator it;
///This should add an element:
lista_komputerow_STL.push_back(Komputer(nazwa));
///This should remove chosen element:
int element;

for(int i=0;i<(element-1);i++)
{it++;}
lista_komputerow_STL.erase(it);

I am completaly new to STL and it seems to be to much for me for now, but I hope that with your help I'll get it.

Upvotes: 2

Views: 223

Answers (1)

Gauthier Boaglio
Gauthier Boaglio

Reputation: 10242

You must initialize the iterator :

list <Komputer>::iterator it = lista_komputerow_STL.begin();

Also the chosen element is not initialized and I suppose that your for statement should be:

int element = 0;
for(int i=0; i<element; i++)      // Without the '-1'
...

And I would suggest to use std::advance to shift the iterator instead of a for loop:

std::advance(it, element);

But you may look at a base example and let me know if there is something you don't get...

Upvotes: 6

Related Questions