使用迭代器擦除矢量中的元素
using iterator to erase element in vector
>我有以下向量来存储类型播放器的元素:
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
可移动。
相关文章:
- 对于set上的循环-获取next元素迭代器
- 访问要输出的矢量迭代器元素
- 为什么这个程序没有打印返回的迭代器的正确第二个元素?
- C++如何乘以包含 std::variant 元素的向量的迭代器?正在执行迭代器类型的转换?
- 调用 erase() 函数是否也会在擦除元素之前更改迭代器值?
- 为什么 min_element() 返回最小元素的索引,而不是迭代器?
- 如何通过查找迭代器结果分配给一组对的元素
- C++:在进行切片时对迭代器的约定,特别是对于访问最后一个元素并最终将其删除
- 将迭代器作为 3 个元素的滑动窗口,可以超调边界(可能使用 Boost)
- C++链表最后一个元素的迭代器?
- 使用索引与迭代器将向量迭代到倒数第二个元素
- 提升堆元素句柄比较和 MSVC 迭代器调试工具
- 如果我有一个指向矢量元素的指针,而不是迭代器,如何删除它?
- 使用迭代器打印矢量元素
- C++ std::vector语言 - 如何修改迭代器指定的元素?
- 你能pop_back一个向量,并且仍然使用迭代器到最后一个元素吗?
- 优先级队列(使用 pairs<int,int> ) 根据 for 循环迭代器的顶级元素
- C++ 当容器在使用前被破坏/修改时发出警告(通过引用元素或迭代器使用)
- 无法将 std::set 中的元素迭代器插入到 std::list
- 使用std :: remove_reference获取STL容器的元素迭代器