STL计数算法返回不正确的值。

时间:2014-05-02 09:01:37

标签: c++ stl stl-algorithm

我必须找到序列的主要元素:

92,19,19,76,19,21,19,85,19,19,19,94,19,19,22,67,83,19,19,54,59,1,19,19

主要元素是在集合中出现的大小/ 2倍。

现在的问题是,在计数92之后,它将从集合中删除值为92的所有元素,之后它将计算19的数量。此序列中19的数量为13,但计数算法为刚回来1。 计数算法只返回序列的第一个元素的正确答案。

这是功能:

int countMajor(vector<int>& v)
{
  int max = (v.size() / 2);
  int c = 0;
  do{
    c = count(v.begin(), v.end(), v[0]);
    if (c > max)
      return v[0];
    v.erase(remove_if(v.begin(), v.end(), [&v](int i){
      if (v[0] == i)
        return true;
      return false;
    }), v.end());
  } while (!v.empty());
  return -1;
}

计数92后,它将被移除,v[1]即19将是新的v[0]。 我无法弄清楚我做错了什么。

1 个答案:

答案 0 :(得分:2)

您正在删除v [0]。

成功:

int e = v[0];
v.erase(remove_if(v.begin(), v.end(), [e](int i){
  if (e == i)
    return true;
  return false;
}), v.end());