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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With