使用.erase(C )的逻辑错误
Logic error using .erase (C++)
,所以我的程序只是读取数字的输入,并按顺序列出它们。如输出所示。没有使用算法库,我对其进行了排序并摆脱了重复的数据。但是,如果重复数据值,则未打印向量的最后值。我是否错误地使用.erase?
void remove_repeated(int size, vector<int>& num_vec){
for(int i = 0; i < num_vec.size(); i++){
if(num_vec[i]==num_vec[i+1]){
num_vec.erase((num_vec.begin()+i));
}
}
}
输出没有重复值时:
**Welcome to the HW Reading Program**
Please, enter your HW:1-10
Do Problems: 1, 2, 3, 4, 5, 6, 7, 8, 9,and 10
重复值时输出:
**Welcome to the HW Reading Program**
Please, enter your HW: 1-10,1-3
Do Problems: 1, 2, 3, 4, 5, 6, 7, 8,and 9
从向量删除索引i
的元素后,下一个元素是index i
,而不是index i+1
。另外,与i+1
相比,您必须注意不要脱离界限,即您的循环必须看起来像这样:
for(int i = 0; i < num_vec.size()-1;){
if(num_vec[i]==num_vec[i+1]){
num_vec.erase((num_vec.begin()+i));
} else {
i++;
}
}
您还应该考虑使用标准库所提供的内容。set
仅包含唯一元素,或者您可以使用erase
unique
(例如,请参阅此处有关更多详细信息)。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- C++ 结构错误"调用'erase'没有匹配函数
- C++映射容器 erase() 分段错误
- C++:具有 const int 的类的 vector.erase 实例给出"attempting to reference a deleted function"错误 C2280
- 调用 vector.erase() 函数时指针操作无效错误
- 使用.erase(C )的逻辑错误
- 产生错误的向量"erase"和"at" (c++)
- 错误 C2280;运算符 =(const Employee &) 在执行 employees.erase() 时出现问题
- 模板化"find-and-erase"函数中的错误
- std::vector<std::ofstream>::erase 给出编译错误
- 类的const成员出现std::deque::erase编译错误
- 错误C2280:试图引用已删除的函数(试图调用vector.erase)
- c++ Vector.erase()导致分段错误
- 调用vector.erase()时出现分段错误