使用迭代器擦除矢量中的元素

using iterator to erase element in vector

本文关键字:元素 迭代器 擦除      更新时间:2023-10-16

>我有以下向量来存储类型播放器的元素:

std::vector<player> players;

在一个名为 Game 的类中,它具有以下功能:

void game::removePlayer(string name) {
  vector<player>::iterator begin = players.begin();
  // find the player
  while (begin != players.end()) {
      if (begin->getName() == name) {
          break;
      }
      ++begin;
  }
  if (begin != players.end())
      players.erase(begin);

}

我收到以下错误:

    1>------ Build started: Project: texas holdem, Configuration: Debug Win32 ------
1>  game.cpp
1>c:program files (x86)microsoft visual studio 10.0vcincludexutility(2514): error C2582: 'operator =' function is unavailable in 'player'
1>          c:program files (x86)microsoft visual studio 10.0vcincludexutility(2535) : see reference to function template instantiation '_OutIt std::_Move<_InIt,_OutIt>(_InIt,_InIt,_OutIt,std::_Nonscalar_ptr_iterator_tag)' being compiled
1>          with
1>          [
1>              _OutIt=player *,
1>              _InIt=player *
1>          ]
1>          c:program files (x86)microsoft visual studio 10.0vcincludevector(1170) : see reference to function template instantiation '_OutIt std::_Move<player*,player*>(_InIt,_InIt,_OutIt)' being compiled
1>          with
1>          [
1>              _OutIt=player *,
1>              _InIt=player *
1>          ]
1>          c:program files (x86)microsoft visual studio 10.0vcincludevector(1165) : while compiling class template member function 'std::_Vector_iterator<_Myvec> std::vector<_Ty>::erase(std::_Vector_const_iterator<_Myvec>)'
1>          with
1>          [
1>              _Myvec=std::_Vector_val<player,std::allocator<player>>,
1>              _Ty=player
1>          ]
1>          c:vcprojectstexas holdemtexas holdemgame.h(29) : see reference to class template instantiation 'std::vector<_Ty>' being compiled
1>          with
1>          [
1>              _Ty=player
1>          ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

删除行

players.erase(begin);

修复错误,为什么会发生,我该如何修复它?

您需要重

载职业玩家的赋值运算符Player & operator= (const Player & other)。这是必需的,因为erase要求它的参数是可复制的(它需要在删除后重新排列向量的其他元素)。

发生的情况是,库代码通过将迭代器上方的每个数组元素推到一个插槽中来删除player对象。为此,它使用 operator= 复制每个对象。显然,类player没有该运算符。

问题是你的Player类是不可移动的。为了从向量中间删除Player,之后的所有Player都必须在向量中向下移动一个空格。一种解决方案是不使用向量。另一个是使Player可移动。