inv*_*ino 0 c++ iterator stl vector erase
我有以下玩具代码,旨在从矢量中删除重复项:
void overlap_removal(vector<int> &vec1, vector<int> &vec2) {
for (vector<int>::iterator it1 = vec1.begin(); it1 != vec1.end(); ++it1) {
for (vector<int>::iterator it2 = vec2.begin(); it2 != vec2.end(); ++it2) {
if ((*it1)*(*it2) < 10) {
vec1.erase();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我在实际代码中做了稍微复杂的比较,但不想混淆问题.问题是分段错误不可避免地跟随执行:我认为这是因为我正在删除一个元素,然后继续循环遍历同一个向量.
如何使代码工作?这甚至是正确的起点吗?提前致谢
Dou*_* T. 10
尝试remove_if.
基本思想是提供一个函数对象,如果传入的元素应该删除,则返回true:
class ItemInOtherVectorPred
{
const std::vector<int>& otherVec;
ItemInOtherVectorPred(const std::vector<int>& vec) : otherVec(vec) {}
// return true if removeVecsElem should be deleted
bool operator()(const int& removeVecsElem) const
{
return (otherVec.find(removeVecsElem) != otherVec.end())
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用该对象的实例告诉remove_if要从向量中删除什么.
void overlap_removal(vector<int> &vec1, vector<int> &vec2)
{
ItemInOtherVectorPred trueIfItemInOtherVecPred( vec2);
vector<int>::iterator eraseBeg =
std::remove_if( vec1.begin(), vec1.end(), trueIfItemInOtherVecPred);
vec1.erase(eraseBeg, vec1.end());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1586 次 |
| 最近记录: |