据称,当迭代器变为无效时,您不能在迭代时擦除/删除容器中的元素.删除满足特定条件的元素的(安全)方法是什么?请只是stl,没有提升或tr1.
编辑 如果我想删除符合某个标准的元素,可能使用仿函数和for_each或擦除算法,是否有更优雅的方法?
请考虑以下情形:
map(T,S*) & GetMap(); //Forward decleration
map(T, S*) T2pS = GetMap();
for(map(T, S*)::iterator it = T2pS.begin(); it != T2pS.end(); ++it)
{
if(it->second != NULL)
{
delete it->second;
it->second = NULL;
}
T2pS.erase(it);
//In VS2005, after the erase, we will crash on the ++it of the for loop.
//In UNIX, Linux, this doesn't crash.
}//for
Run Code Online (Sandbox Code Playgroud)
在我看来,在VS2005中,在"擦除"之后,迭代器将等于end(),因此在尝试增加它时崩溃.在这里呈现的行为中,编译器之间是否存在真正的差异?如果是这样,"擦除"之后的迭代器将在UNIX/Linux中等于什么?
谢谢...
我对我的一段代码感到担忧.我有组件和存储组件的对象.问题是在组件可以告知从对象中删除组件的更新期间.但它从另一个功能调用.
void Object::update() { //using std::map here
for(ComponentMap::iterator i = components.begin(); i != components.end(); ++i) {
(*i).second->update();
}
}
void HealthComponent::update() {
if(health <= 0) object->removeComponent("AliveComponent"); //this is wrong logic. but its just an example :D
}
void Object::removeComponent(string component) {
ComponentMap::iterator i = components.find(component);
if(i == components.end()) return;
components.erase(i);
}
Run Code Online (Sandbox Code Playgroud)
并假设我有很多组件 - 健康,活着,图形,物理,输入等.
我试过这样的东西(带有一些测试组件)并且在更新期间没有错误.但我真的很担心.它可以在将来给我一个错误吗?如果是的话,如何解决?
提前谢谢,
Gasim
也许你可以用我目前遇到的问题来启发我.所以问题是当我试图擦除地图中的某些元素时,我得到了一个糟糕的访问内存.我们假设以下typedef:
typedef std::map < std::string *, Document *, pStringCompare > Map;
Run Code Online (Sandbox Code Playgroud)
我们假设在执行以下所有代码之前,我们已经实例化了一个包含两个元素的映射(例如).这段代码很棒:
Map::iterator it = documents.begin();
std::string *s = it->first;
Document *d = it->second;
documents.erase(it);
delete d;
delete s;
Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用迭代器循环时,我得到了错误.
for (Map::iterator it = documents.begin() ; it != documents.end() ; it++)
{
std::string s = * ( it->first);
Document dd = * (it->second);
std::cout << s << " || " << dd;
documents.erase(it); // This line causes the bad access memory error.
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助 …
我通过以下方式使用擦除从地图中删除元素,但它无法正常工作.为什么?它并没有全部删除.
float nw_cut=80.0;
for(it=nw_tot1.begin();it!=nw_tot1.end();it++)
{
float f=(float) ((float) it->second/lines)*100.0;
if ( f < nw_cut )
{
nw_tot1.erase(it);
}
}
Run Code Online (Sandbox Code Playgroud)