0

I'm learning container list. And I want to write function to replace (element on index), insert (element on index), and I want to know how to delete them. I'm learning this about two day I watched videos and read articles but I just don't know how to write this code. I know how list work's with pointers.

This is how I imagined (it is just a start)

void replace(list<Contact> &listOf, int index, const Contact &information) { for(list<int>::iterator it = listOf.begin(); it != listOf.end(); it++){ } } 

I don't know if the for loop is writen right, but I imagined that it go through list and if it finds index which wants to replace it will juse overwrite.

I think function insert has the same parameters.

And this is how I imagined for delete it but i'm not quit sure how to implement.

Contact delete(list<Contact> &listOf, int index) { } 

I have created strutcture of Contact with name and surname both string on the start of the program.

2 Answers 2

1

The loop should be written

for (list<Contact>::iterator it = listOf.begin(); it != listOf.end(); ++it) { do what you wan't with *it. } 
Sign up to request clarification or add additional context in comments.

Comments

1

A list has no random access so is not appropriate for such manipulation. If you insist, here is a way to avoid writing a loop yourself:

void replace(list<Contact> &listOf, int index, const Contact &information) { list<int>::iterator it = listOf.begin(); std::advance(it, index); *it = information; } 

Use std::vector for random access operations. Use std::list for modifications like insertion or deletion in the middle of the container.

2 Comments

Can you show me how is proper manipulation with list. I would be happy if you could show me the whole code how to do replace. If it's possible? I realy want to know how to do those functions. Thanks
Look at the std::list reference. Methods a list is particularly good at compared to other containers are e.g. insert, erase, merge, or splice, assuming that you have iterators pointing to elements within the list. If you only have an index, then std::advance can be used as above to obtain an iterator, then apply one of list's methods. But keep in mind that this is very inefficient. Most likely it's better to use a vector in this case, even if the corresponding methods are not as efficient as list's.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.