问题描述:

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 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.

相关阅读:
Top