Remove all elements from QVector which are smaller than 0

Viewed 4734

I have a QVector

 QVector(48, 64,  31, -2, 14, 5, 7, -3, -1, 13) 

I want to know how to use Qt mechanism to remove all the elements that are smaller than 0.

How do I do this in a simple way?
Thanks

2 Answers

QVector's interface allows it to be used with the std algorithms, so you can just use the erase-remove idiom

QVector<int> vec;
...
vec.erase(std::remove_if(vec.begin(), vec.end(), [](int i) { return i < 0; }), 
          vec.end());

By way of explanation:

remove_if takes a range of iterators (vec.begin(), vec.end()), and moves all elements for which the provided lambda returns true to the end. It then returns an iterator to the beginning of this range.

erase takes a range of iterators (the returned value from remove_if and vec.end()) and erases them from the vector.

Working example:

#include <QVector>
#include <iostream>

int main()
{
    QVector<int> vec { 1, 2, 3, -1, -2, -3, 4, 5, 6, -7, -8, -1, 1, 2, 3 };

    // erase all elements less than 0
    vec.erase(std::remove_if(vec.begin(), vec.end(), [](int i) { return i < 0; }),
              vec.end());

    // print results
    for (int i : vec)
        std::cout << i << ' ';
    std::cout << '\n';

    return 0;
}

Output:

./a.out  
1 2 3 4 5 6 1 2 3
// Create your list
QVector<int> listIntegers;
... 

// Remove all numbers < 0 from QVector<int> 
QMutableVectorIterator<int> i(listIntegers);
while (i.hasNext()) {
    if (i.next() < 0)
        i.remove();
}

You can also adapt this piece of code to do what you want, just by changing the condition inside the while loop.

Related