Find and erase element from STL container while iterating - c++

While iterating over a multimap I want to delete elements, but not only the element the iterator is pointing to.
for (vector<int> myVec : myVectors)
{
auto range = myMultiMap.equal_range(myVector);
for (auto it = range.first; it != range.second; ++it)
{
// secondPair is another element of this multimap
auto secondPair = getSecondPair(it, myMultiMap);
if (condition)
{
it = myMultiMap.erase(it);
auto finder = myMultiMap.find(secondPair);
// how can I delete secondPair?
}
}
}
Maybe it's the xy-problem here, so let me explain what I need this for: What I'm trying to do is to shorten a set of vector<int>. There are associated elements of type MyPair for each element. Those associated elements are stored in an unordered multimap.
typedef unordered_multimap < vector<int>, MyPair, SomeHash > MyMultiMap;
An element of the set<vector <int> > can be removed if all associated pairs in the multimap have been processed successfully. It won't be successful for most of them, so most of them are expected to remain in the set. My idea was to delete the elements from the multimap and if there are no associated elements in the multimap anymore, it means the element can be removed from the set.
Here again I have the problem to remove elements from a set while iterating. Again, not only the one the iterator is pointing to.

From cppreference on unordered_multimap::erase:
References and iterators to the erased elements are invalidated. Other iterators and references are not invalidated.
So I think that if you get an iterator to secondPair and secondPairIt != it then you can safely erase secondPairIt. You should also check that you are not invalidating the end of the range.
for (auto it = range.first; it != range.second;)
{
if (condition)
{
auto secondPairIt = getSecondPairIt(it, myMultiMap); // Assume this is not end
if (secondPairIt != it)
{
if (secondPairIt == range.second)
range.second = myMultiMap.erase(secondPairIt);
else
myMultiMap.erase(secondPairIt);
}
it = myMultiMap.erase(it);
}
else
{
++it;
}
}

Related

How can I code a loop that compares every element of an unordered_set with all the others, using iterators in C++?

I have an unordered_set and I need to pick each element and compare it with all the others.
Notes:
If A and B are compared, I don't need to compare B and A.
My unordered_set is the value of an unordered_map, for which the key is a pair.
I tried the following:
unordered_map <pair<int, int>, unordered_set <int>, boost::hash<std::pair<int,int>>> gridMap;
unordered_map <int, rigidBody*> objectsMap;
auto gridMapIt = gridMap.begin();
while (gridMapIt != gridMap.end()) // loop the whole gridMap
{
auto setItOut = gridMapIt->second.begin();
while (setItOut != gridMapIt->second.end()) // loop each element of the set
{
auto setItIn = gridMapIt->second.begin();
while (setItIn != gridMapIt->second.end()) // versus each other element
{
//compare and do stuff
++setItIn;
}
checked.insert({ objectsMap[*setItOut]->getID(), objectsMap[*setItIn]->getID() });
checked.insert({ objectsMap[*setItIn]->getID(), objectsMap[*setItOut]->getID() });
++setItOut;
}
++gridMapIt;
}
The error I am getting is "Expression: cannot dereference end list iterator". If I remove or comment the innermost while loop, it works fine.
Thanks in advance.
The use of *setItIn after the loop is invalid. At that point you have an iterator that points past the last element. That's what the error is telling you.
If you change from while to for you can use the scoping rules to stop yourself from dereferencing invalid iterators.
Rather than populate checked, you can start the inner loop from the next element, rather than the first.
for (auto & gridElem : gridMap) {
for (auto setItOut = gridElem.second.begin(), setEnd = gridElem.second.end(); setItOut != setEnd; ++setItOut) {
for (auto setItIn = std::next(setItOut); setItIn != setEnd; ++setItIn) {
//compare and do stuff
}
// setItIn not visible here
}
}

Erase nested map elements

I have a map which looks like
typedef std::map<int, std::set<float>> innerMap;
typedef std::map<long, innerMap> outerMap;
I want to do following:
1. I want to erase inner map elements for a key of outer map.
2. Then I want to erase outer map key if it contains 0 inner map elements.
For first scenario, I have written code as:
outerMap mapA;
//assuming this map contain an element
//longx is key in outer element, intx is key of inner element
std::map<int, std::set<float>>::const_iterator innerIter = mapA[longx].begin();
while (innerIter != mapA[longx].end())
{
if (innerIter->first == intx)
{
if (innerIter->second.size() == 0)
{
mapA[longx].erase(innerIter++);
}
break;
}
++innerIter;
}
I have written this code in C++ but I wanna use C++11. Can we write this in a better way in C++11?
For second scenario, do I need to iterate again outer map and check its value elements or I can do it in existing code itself?
This code looks way too complicated to me. The following should do the same, no need to use fancy C++11 features:
outerMap mapA;
// Lookup iterator for element of outerMap.
outerMap::iterator const outerIter = mapA.find(longx);
// Lookup iterator for element of innerMap that should be checked.
innerMap::const_iterator const innerIter = outerIter->second.find(intx);
// Check if element of innerMap should be erased and erase it if yes.
if(innerIter != outerIter->second.end() && innerIter->second.size() == 0) {
outerIter->second.erase(innerIter);
}
// Erase element of outer map is inner map is now empty:
// This should do scenario 2
if(outerIter->second.size() == 0) {
mapA.erase(outerIter);
}
what you do currently (in C++11):
auto& inner = mapA[longx];
const auto it = inner.find(intx);
if (it != inner.end() && it->second.size() == 0) {
inner.erase(it);
}

C++ Remove Objects in List at Loop

How can i delete all objects which are works finished
I using the following code but get list iterator not incrementable
How can I remove it without deleting it
list<A*> myList;
for(list<A*>::iterator it = myList.begin(); it !=myList.end(); ++it ){
(*it )->DoSomething();
if((*it )->WorksFnished()){
//myList.erase(it ); <- It's works but I get exception after the loop
//myList.remove(*it ); <- It's works but I get exception after the loop
}
}
erase returns an iterator
list<A*> myList;
list<A*>::iterator it = myList.begin();
while( it != myList.end() ) {
(*it)->DoSomething();
if( (*it)->WorksFnished() ) {
it = myList.erase(it);
} else {
++it;
}
}
You can make use of the fact that erase returns a new iterator, as described in other answers here. For performance-critical code, that might be the best solution. But personally, I would favor splitting the loop into separate processing and removal steps for readability and clarity:
// Assumes C++ 11 compatible compiler
list<A*> myList;
// Processing
for(const auto* each : myList){
each->DoSomething();
}
// Deletion
myList.remove_if([](A* each) {
return each->WorksFnished();
});
If you don't want to use remove_if, some alternatives are:
Copy all objects you want to keep into a new list, then std::swap it with your current list
Use a temporary list toBeRemoved, and add all objects that should be removed to that. When you're finished iterating over the actual list, iterate toBeRemoved and call myList.erase for each element
Some workaround..
increment the number of objects from the list that has WorkFnished.
then after the loop. if the accumulator match the list size, clear it.
size_t nFinished = 0;
list<A*> myList;
for(list<A*>::iterator it = myList.begin(); it !=myList.end(); ++it ){
(*it )->DoSomething();
if((*it )->WorksFnished()){
nFinished++;
}
}
if (nFinished == myList.size())
{
myList.clear();
}
If you use erase you have to assign it back to the iterator. In this case, we have to take care of the incrementing ourselves depending if the current element was erased or not.
list<A*> myList;
for (auto it = myList.begin(); it != myList.end(); )
{
(*it)->DoSomething();
if( (*it)->WorksFnished() ) {
it = myList.erase(it); // Sets it to the next element
} else {
++it; // Increments it since no erasing
}
}
std::list::erase
Return: An iterator pointing to the new location of the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.

Erase element in vector while iterating the same vector [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Erasing from a std::vector while doing a for each?
I'm trying to implement vertice coloring according to this algorithm;
/*
Given G=(V,E):
Compute Degree(v) for all v in V.
Set uncolored = V sorted in decreasing order of Degree(v).
set currentColor = 0.
while there are uncolored nodes:
set A=first element of uncolored
remove A from uncolored
set Color(A) = currentColor
set coloredWithCurrent = {A}
for each v in uncolored:
if v is not adjacent to anything in coloredWithCurrent:
set Color(v)=currentColor.
add v to currentColor.
remove v from uncolored.
end if
end for
currentColor = currentColor + 1.
end while
*/
I don't understand "add v to currentColor." line but I supposed, it means assing currentColor to v. Therefore what is the "set"? Anyway the problem is erasing element in vector while iterating it. This is the code.
vector<struct Uncolored> uc;
vector<struct Colored> c;
int currentColor = 0;
struct Colored A;
struct Colored B;
vector<struct Uncolored>::iterator it;
vector<struct Uncolored>::iterator it2;
vector<struct Colored>::iterator it3;
for(it=uc.begin();it<uc.end();it++){
A.id = (*it).id;
uc.erase(uc.begin());
A.color = currentColor;
c.push_back(A);
for(it2=uc.begin();it2<uc.end();it2++) {
it3=c.begin();
while(it3 != c.end()) {
if( adjacencyMatris[(*it2).id][(*it3).id] == 0 ) {
B.id = (*it2).id;
it2 = uc.erase(it2);
B.color = currentColor;
c.push_back(B);
}
it3++;
}
}
currentColor = currentColor + 1;
}
I think it2 = uc.erase(it2); line is already general use but It gives run time error.
In the line:
it2 = uc.erase(it2);
an element pointed by iterator it2 is removed from the vector, elements are shifted in memory in order to fill that gap which invalidates it2. it2 gets a new value and now points to the first element after the the removed one or the end of the vector (if removed element was the last one). This means that after erasing an element you should not advance it2. An alternative to proposed remove-erase idiom is a simple trick:
for(it2 = uc.begin(); it2 != uc.end();)
{
...
if(...)
{
it2 = uc.erase(it2);
}
else
{
++it2;
}
...
}
You can read more about this here.
Edit:
Regarding your comment, you can use a flag to pass the information whether an element has been erased or not, and you can check it when you get out from the inner loop:
for(it2=uc.begin(); it2 != uc.end();)
{
bool bErased = false;
for(it3 = c.begin(); it3 != c.end(); ++it3)
{
if(adjacencyMatris[(*it2).id][(*it3).id] == 0 )
{
B.id = (*it2).id;
it2 = uc.erase(it2);
bErased = true;
B.color = currentColor;
c.push_back(B);
break;
}
}
if(!bErased)
++it2;
}
After you've erased an element from uc you need to break from the inner loop. In the next iteration of the outer loop you'll be able to access the next element in the uc through a valid iterator.
Instead of working with iterator types, store an index into the vector. When you need an iterator--perhaps for passing into erase--you can say begin() + myIndex to generate an iterator.
This also makes the loop look more familiar, e.g.
for(ind=0; ind < uc.size(); ind++) {
vector::erase() can invalidate iterators pointing to the vector.
This invalidates all iterator and references to position (or first) and its subsequent elements.
You need to add the result of erase to the iterator (it will point to the element just after the one erased) and use that consequently. Note that in
for(it=uc.begin();it<uc.end();++it){
A.id = (*it).id;
uc.erase(uc.begin());
...
}
The iterator it is not valid after uc.erase, so subsequent ++ and use might result in runtime error.
Similarly, even though you assign the result of erase to it2, the call can invalidate it, which is not changed.
Your best bet is either to re-start your algorithm from the beginning after each erase(), or if you can alter it so that it can continue from the iterator returned by erase, do that to gain some efficiency.
You've got the runtime error because it2 = uc.erase(it2); returns the iterator following the last removed element, so the it2++ in for(it2=uc.begin();it2<uc.end();it2++) goes beyond the last element.
Try changing your if in:
if( adjacencyMatris[(*it2).id][(*it3).id] == 0 ) {
B.id = (*it2).id;
uc.erase(it2);
B.color = currentColor;
c.push_back(B);
break;
}

STL Multimap Remove/Erase Values

I have STL Multimap, I want to remove entries from the map which has specific value , I do not want to remove entire key, as that key may be mapping to other values which are required.
any help please.
If I understand correctly these values can appear under any key. If that is the case you'll have to iterate over your multimap and erase specific values.
typedef std::multimap<std::string, int> Multimap;
Multimap data;
for (Multimap::iterator iter = data.begin(); iter != data.end();)
{
// you have to do this because iterators are invalidated
Multimap::iterator erase_iter = iter++;
// removes all even values
if (erase_iter->second % 2 == 0)
data.erase(erase_iter);
}
Since C++11, std::multimap::erase returns an iterator following the last removed element.
So you can rewrite Nikola's answer slightly more cleanly without needing to introduce the local erase_iter variable:
typedef std::multimap<std::string, int> Multimap;
Multimap data;
for (Multimap::iterator iter = data.begin(); iter != data.end();)
{
// removes all even values
if (iter->second % 2 == 0)
iter = data.erase(iter);
else
++iter;
}
(See also answer to this question)