我有 2 个 vector vc
和 v2
我想从 vc
中删除 v2 中包含的所有元素。
我尝试通过 2 个嵌套循环来执行此操作。然而,编译器给出了一个错误:Debug Assertion Failed
。我想问一下为什么会这样,我该如何解决?
提前致谢!
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector <string> vc;
vector <string> v2;
int main()
{
vc.push_back("ala");
vc.push_back("bala");
vc.push_back("test");
vc.push_back("sample");
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
v2.push_back("test");
v2.push_back("bala");
for (auto i = vc.begin(); i != vc.end(); i++) {
for (auto j = v2.begin(); j != v2.end(); j++) {
if (i == j) {
vc.erase(i);
}
}
}
//it should print only ala and sample after the removal process, but it gives
//debug assertion error
for (int i = 0; i < vc.size(); i++) {
cout << vc[i] << endl;
}
}
最佳答案
正如评论中所指出的,您的代码段中有两次未定义的行为。首先,您比较两个不引用同一容器的迭代器。二、vc
迭代器和循环变量 i
当 vc.erase(i)
时失效被称为。
解决这个问题是利用 <algorithm>
的一个很好的例子 header 和常见习语,因为手动实现这些东西很容易出错。你需要的是所谓的erase-remove-idiom :
#include <algorithm>
auto isInV2 = [&v2](const auto& element){
return std::find(v2.cbegin(), v2.cend(), element) != v2.cend(); };
vc.erase(std::remove_if(vc.begin(), vc.end(), isInV2), vc.end());
根据您的应用程序的情况,保持 vector 排序(或在某个点对它们进行排序)然后使用二进制搜索来检查是否存在元素可能也是合适的,这样可以更好地扩展更大的序列。
auto isInV2LogN = [&v2](const auto& element){
return std::binary_search(v2.cbegin(), v2.cend(), element); };
// Important: v2 must be sorted, otherwise std::binary_search doesn't work:
std::sort(v2.begin(), v2.end());
vc.erase(std::remove_if(vc.begin(), vc.end(), isInV2LogN), vc.end());
关于c++ - 在 C++ 中从一个 vector 中删除另一个 vector 中包含的所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53627269/