vector<T>我的程序中有两个active,non_active分别称为和.这是指它包含的对象,以及它们是否在使用中.
我有一些代码循环active向量并检查可能已经非活动的任何对象.我将这些添加到temp_list循环内部.
然后之后的循环,我把我temp_list做non_active.insert的所有元素temp_list.
在那之后,我会调用erase我的active矢量并将其传递temp_list给擦除.
然而,由于某种原因,erase崩溃.
这是代码:
non_active.insert(non_active.begin(), temp_list.begin(), temp_list.end());
active.erase(temp_list.begin(), temp_list.end());
Run Code Online (Sandbox Code Playgroud)
我得到这个断言:
Expression:("_Pvector == NULL || (((_Myvec*)_Pvector)->_Myfirst <= _Ptr && _Ptr <= ((_Myvect*)_Pvector)->_Mylast)",0)
Run Code Online (Sandbox Code Playgroud)
我在网上看过,看到有一个删除删除的成语,但不知道我是如何应用它来删除一系列元素 vector<T>
我没有使用C++ 11.
erase期望传递给它的一系列迭代器位于当前向量中.您不能将从不同向量获取的迭代器传递给erase.
这是lambda支持的可能但效率低下的C++ 11解决方案:
active.erase(std::remove_if(active.begin(), active.end(), [](const T& x)
{
return std::find(temp_list.begin(), temp_list.end(), x) != temp_list.end();
}), active.end());
Run Code Online (Sandbox Code Playgroud)
这里是没有lambda的等效C++ 03解决方案:
template<typename Container>
class element_of
{
Container& container;
element_of(Container& container) : container(container) {}
public:
template<typename T>
bool operator()(const T& x) const
{
return std::find(container.begin(), container.end(), x)
!= container.end();
}
};
// ...
active.erase(std::remove_if(active.begin(), active.end(),
element_of<std::vector<T> >(temp_list)),
active.end());
Run Code Online (Sandbox Code Playgroud)
如果temp_list用a 替换std::set并std::find_if使用find成员函数调用,则性能应该是可接受的.