如何检查擦除 - 删除操作是否成功?

时间:2017-05-18 08:43:29

标签: c++ erase-remove-idiom

这是我第一次使用这个成语,我有一个向量v1,其元素必须是另一个向量v2中元素的子集。现在,想象v1v2作为集合,我想执行v2-v1并在v1[i]v2不存在时抛出异常(对于i任何有意义的std::vector<T> v1; std::vector<T> v2; //fill v1, v2 somehow for(size_t i=0; i<v1.size(); i++){ v2.erase(std::remove(v2.begin(), v2.end(), v1[i]), v2.end()); if(/*erase option failed because v1[i] doesn't exists in v2*/) throw std::runtime_exception (std::to_string(i)+"-th in v1 doesn't exists in v2!"); } )。

我想出了这个:

if

如何填写{{1}}条件?

1 个答案:

答案 0 :(得分:6)

只需检查是否删除了任何元素:

const auto orig_size = v2.size();
v2.erase(std::remove(v2.begin(), v2.end(), v1[i]), v2.end());
if (v2.size() == orig_size)

或者将其拆分(没有任何东西强迫你在一个语句中删除和删除):

const auto last = std::remove(v2.begin(), v2.end(), v1[i])
if (last == v2.end())
  throw std::runtime_exception (std::to_string(i)+"-th in v1 doesn't exists in v2!");
v2.erase(last, v2.end());

如果您保持两个向量排序并使用算法一起遍历它们,您可以使代码更有效。您当前的代码是O(n²),因为它会搜索v2v1中每个元素的整个[[UIApplication sharedApplication] openURL:@"123"];