3
#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    enum class En{A, B};
    std::vector<En> vec{En::A, En::B, En::A, En::B, En::A, En::B, En::A};
 
    for(const auto& i : vec) std::cout << int(i) << ", ";
    std::cout << std::endl;

    vec.erase(std::remove(std::begin(vec), std::end(vec), vec.front()), 
              std::end(vec));

    for(const auto& i : vec) std::cout << int(i) << ", ";
    std::cout << std::endl;

    return 0;
}

Ideone: http://ideone.com/NTPVyE

Prints:

0, 1, 0, 1, 0, 1, 0,

1, 0, 0, 0,

Why is this happening? Shouldn't only the first element of the vector be removed?

I suppose std::remove doesn't stop at the first element, but runs through the whole vector. Is there any way I can use the erase-remove idiom on collections with non-unique elements?

4

1 回答 1

7

第三个参数std::removeconst引用。当您四处移动元素时,您正在更改引用的元素的值,从而导致未定义的行为。

这将表现良好:

auto elem = vec.front(); // copy front element
vec.erase(std::remove(std::begin(vec), std::end(vec), elem), 
          std::end(vec));

输出:

1, 1, 1,

于 2014-01-12T11:30:35.040 回答