矢量擦除错误
Vector Erase Error
我在c++中有以下代码:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
int main ()
{
srand(time(0));
int noOfElements = 9;
for (int a = 0; a < 9; a++)
{
std::vector<int> poss;
for (int a = 1; a <= 9; a++)
poss.push_back(a);
for (int b = 0; b < 9; b++)
{
int random = rand() % 9;
std::cout << poss[random];
poss.erase(random);
noOfElements--;
}
std::cout << "n";
}
}
但是当我运行它时,它返回这个:
error: no matching function for call to 'std::vector<int>::erase(int&)'
第13行
为什么会这样,我该如何纠正?
不能直接从vector容器中擦除值 (vector是序列容器,而不是关联容器):需要为要擦除的元素提供一个迭代器。
要获得迭代器,可以:
- 根据其值查找元素(例如使用
std::find()
),然后将返回的迭代器作为输入提供给erase()
成员函数,或者 - 通过对指向vector开头的迭代器(即由
begin()
成员函数返回的对象)应用偏移量来获得它。
第一种情况:
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> v { 1, 2, 3};
auto i = std::find(begin(v), end(v), 2);
v.erase(i);
}
上面的代码使用了一些c++ 11的特性。在c++ 03中,它看起来像这样:
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
std::vector<int>::iterator i = std::find(v.begin(), v.end(), 2);
v.erase(i);
}
在第二种情况中,如果您知道向量内元素的索引(例如,pos
),那么您可以通过这种方式轻松获得迭代器:
v.begin() + pos
或者(仅限c++ 11)您可以这样做:
next(begin(v), pos);
必须传递一个迭代器来擦除。所以尝试
poss.erase(poss.begin() + random);
Vector擦除函数接受迭代器而不是value。你还需要检查边界条件以确保你要擦除的索引没有越界。
std::vector<int>::iterator itr = poss.begin() + random;
if(itr != poss.end())
{
poss.erase(itr);
}
相关文章:
- 双链表的擦除值函数,未知错误
- 分割错误:向量中的擦除功能
- 编译错误 std::vector<std::shared_ptr<T>>迭代器和擦除方法
- 矢量擦除调用的错误析构函数
- 从 C++ 中的集合中擦除时出现分段错误
- 矢量擦除错误,无法删除不完整的类型
- std::map 擦除 - 将迭代器传递给错误的映射
- 删除[]是否可以与通用数组正常使用?如果是这样,为什么使用std :: vector ::擦除它会导致释放内存的错误
- 为什么这种类型的擦除实现(简化的 boost:any)会出现分段错误
- 擦除标准::列表项时的错误
- C++ 从矢量擦除时出现分割错误
- 当我在c++中擦除向量时,我遇到了双自由错误
- 地图擦除错误
- 2D 矢量中的擦除行 - 分割错误
- 擦除矢量时出现分割错误
- C++映射擦除错误
- 为什么擦除End-Iterator不会给shared_ptr分段错误
- 矢量擦除函数删除错误的对象
- 矢量擦除错误
- 从向量c++中擦除对象时出现分段错误