How do I use std:vector's erase() function properly?
I am having a strange issue when using the erase() function on a std:vector. I use the following code:
int count = 0;
for (int itr=0; itr<b.size(); ++itr) {
if (b[count].notEmpty = false) {
b.erase(b.begin()+count);
--count;
}
++count;
}
However, for some reason there are no elements actually getting erased from b. b is declared elsewhere as follows:
vector<block_data> b;
Where block_data is a structure, and contains the boolean value notEmpty. Some of b's elements are properly being assigned with notEmpty = false earlier in the code, so I am not sure why they aren't getting erased. Is it an error with开发者_如何学Python the syntax, or something else?
There's nothing wrong with your use of erase
. The problem is an assignment inside the if
condition:
if(b[count].notEmpty = false)
This sets b[count].notEmpty
to false
, then returns false
. This will cause the inner-body of the if-statement to never run.
Change it to
if(b[count].notEmpty == false)
or event
if(!b[count].notEmpty)
And you should be good to go.
Others have pointed out how to fix your code, but just in case: how to use a Standard algorithm.
// Decide if an element is to be removed
auto predicate = [](block_data& b)
{
// more idiomatic than b.notEmpty == false
return !b.notEmpty;
});
// Remove
auto removed = std::remove_if(b.begin(), b.end(), predicate);
// Count
auto count = b.end() - removed;
// Erase.
b.erase(removed, b.end());
b[count].notEmpty = false
should be b[count].notEmpty == false
, otherwise the if
will always be false
.
Better practice to write false == b[count].notEmpty
, in this way the constant on the left is not an l-value, and if you make the (quite common) mistake of writing =
instead of ==
you'll get a compilation error.
精彩评论