Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. What is the difference between erase, removeAll, removeOne, removeAt in QList?

What is the difference between erase, removeAll, removeOne, removeAt in QList?

Scheduled Pinned Locked Moved General and Desktop
2 Posts 2 Posters 4.6k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • O Offline
    O Offline
    opengpu
    wrote on last edited by
    #1

    what is the difference between erase, removeAll, removeOne, removeAt in QList?
    should i write delete p; p = NULL; before or after (erase, removeAll, removeOne, removeAt) operation?
    thank you

    1 Reply Last reply
    0
    • B Offline
      B Offline
      Binary91
      wrote on last edited by
      #2

      To remove all occurrences of a specific string, you use QStringList::removeAll(QString);
      To remove only the first occurence of a specific string, you use QStringList::removeOne(QString);
      To remove only the first string ("Hello"), you use QStringList::removeFirst();
      To remove a string at a specific position, you use QStringList::removeAt(int pos);
      erease is only useful in combination with iterators, because it also removes items (i.e. the iterator's item) and returns the iterator for the next item that is now at the position of the currently removed item...

      Let's take a look at a QStringList (QList with strings) like this:
      @QStringList list;
      list << "Hello" << "I'm" << "a" << "list" << "Hello";
      list.removeAll("Hello"); // list now: "I'm a list";
      list.removeOne("Hello"); // list now: "I'm a list Hello";
      list.removeFirst(); // list now: "I'm a list Hello";
      list.removeAt(3); // list now: "Hello I'm a Hello";@

      Only removing those items doesn't delete them, since they were allocated dynamically, so yes, AFAIK you still have to delete them. So the better way would be removing and getting its pointer with takeFirst(), takeAt(int pos), takeLast()...

      Example:
      @QList<QPushButton*> list;
      list.append(new QPushButton("Hello"));
      list.append(new QPushButton("Bye"));

      delete list.takeLast(); // removes and deletes the last QPushButton;
      @
      To remove and delete all items, you'll have to do it with a loop:
      @while(!list.isEmpty())
      delete list.takeFirst();@

      Hope that helps ;-)

      1 Reply Last reply
      1

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved