I have a QList variable. How can I erase all the elements starting from an X index and removing all the subsequents N elements taking care of freeing also the memory?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First of all, you should never use
MyClass*to “own” (i.e. control the lifetime of) an instance ofMyClass. Thus, a list ofMyClass*shouldn’t “own” any instances ofMyClass, either. Thus you wouldn’t ever use thedeleteoperator with any of these pointers (and a straydeleteoutside a smartpointer implementation should almost always raise a few eyebrows).QListis in fact a type optimized for a similar use-case. AQList<MyClass>will internally store a dynamic array ofMyClass*(ifMyClassis larger than a pointer), so re-ordering and expanding the list is potentially cheaper. However, if you need to remove elements from the list without deleting them, you should use aQList<unique_ptr<MyClass>>or similar. Either way, you wouldn’t have to worry about the objects’ lifetimes; you’d only need to remove them from the list.Now that I said that, there are a few useful STL idioms that will help achieving what you’re looking for, and they also apply to (most) Qt containers (edit: fixed the removal, added a few helpful comments):
It’s even simpler still, if you meant to remove all elements after
myList[X - 1](in short, replacerange_endwithmyList.end()).