Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all elements from QVector which are smaller than 0

Tags:

qt

qvector

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

like image 824
Theodore Tang Avatar asked Mar 07 '23 12:03

Theodore Tang


1 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
like image 78
Steve Lorimer Avatar answered Mar 23 '23 11:03

Steve Lorimer