C++ STL vector iterators incompatible - c++

// Erase the missing items
vector<AlignedFDRData>::size_type StandardNum = FDRFreq.at(0).fData.size();
vector<AlignedFDRData>::iterator iter = FDRFreq.begin();
while (iter != FDRFreq.end()){
if( iter->fData.size() < StandardNum){
FDRFreq.erase(iter);
}
else{
++iter;
}
}
This part is used to erase the FDRFreq vector item, in which the data length is smaller than the standard number, but the debug assertion failed: vector iterators incompatible. I am a green hand in C++ STL, thanks for your kindly help.

Your problem is iterator invalidation after the call to std::erase. The warning is triggered by an iterator debugging extensions in your standard library implementation. erase returns an iterator to the new valid location after the erase element and you continue iterating from there. However, this is still very inefficient.
Use the Erase-Remove Idiom to remove data with a predicate from a vector.
FDRFreq.erase(std::remove_if(
begin(FDRFreq), end(FDRFreq),
[&StandardNum](const AlignedFDRData& x) {
return fData.size() > StandardNum; }),
end(FDRFreq));

Your code needs to become
while (iter != FDRFreq.end()){
if( iter->fData.size() < StandardNum){
iter = FDRFreq.erase(iter);
}
else{
++iter;
}
}
"vector iterators incompatible" means that the iterator you're using has been invalidated - that is to say, there is no guarantee that the elements it points to still exist at that memory location. An erase of a vector element invalidates the iterators following that location. .erase returns a new, valid iterator you can use instead.
If you're new to STL, I highly recommend you read Scott Myer's Effective STL (and Effective C++, while you're at it)

Related

looping on the same vector legal in C++

Sorry, I know there are questions where people ask how to remove duplicates, but I thought this warranted a new thread since there is something weird coming out of my compiler.
vector<string> removeDuplicates(vector<string> vector)
{
for (vector<string>:: const_iterator it = vector.begin(); it != vector.end(); ++it)
{
for (vector<string>:: const_iterator sit = vector.begin(); sit != vector.end(); ++sit)
{
if(it != sit)
{
if(*it == *sit)
{
vector.erase(it);
}
}
}
}
return vector;
}
I don't understand why it's giving me errors. I am kinda new to C++, so the question might sound kinda dumb. Is it because I am looping on the same vector?
You do not want to erase 1 item at a time. Use the remove-erase pattern which will erase all the elements that should be removed at 1 time, instead of several erase calls. In this case (as you appear to want to remove all duplicate elements), you can copy the vector to a std::set (which will not allow copies) and then assign it back.
The error message appears to be showing a bug in your implementation. std::vector::erase is supposed to be able to take a const_iterator (see quote from the standard below), but the error message you are seeing is indicating your implementation does not have it defined that way.
ยง 23.3.6.5
iterator erase(const_iterator position);
iterator erase(const_iterator first, const_iterator last);
You will also get undefined behavior with your current implementation as the iterator is invalidated once it is erased, so the it++ will not be valid in the loop condition.
If you switch to the more efficient removal methods, this would likely fix that problem as well.
Set Method
std::vector<std::string> vec;
// fill vector with duplicates
std::set<std::string> sVec(vec.begin(), vec.end()); // copies the vector into a set, duplicates removed
vec.assign(sVec.begin(), sVec.end()); // pushes the data in the set back to the vector
Remove/Unique-Erase Method (assuming order does not matter)
std::vector<std::string> vec;
// fill vector with duplicates
std::sort(vec.begin(), vec.end());
vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
When an item in the vector is erased , use the valid iterator which the erase() returns.
like , iterator = vector.erase(iterator)
Also, when you happen to erase the last item in the vector, doing a ++iterator will not work.
This link may help vector erase iterator
I think, the conditions should be :
if(it != sit)
{
if(*it == *sit)
{
sit = vector.erase(sit)
}
else
{
++sit;
}
}
And don't increment sit in for loop
Remove the constness of the iterator which you are erasing. Make sit as vector::iterator.
Do this:
it = vector.erase(it);

update map value

I have a map like this:
map<prmNode,vector<prmEdge>,prmNodeComparator> nodo2archi;
When I have to update the value (vector), I take the key and his value, I update the vector of values, I erase the old key and value then I insert the key and the new vector. The code is this:
bool prmPlanner::insert_edgemap(int from,int to) {
prmEdge e;
e.setFrom(from);
e.setTo(to);
map<prmNode,vector<prmEdge> >::iterator it;
for (it=nodo2archi.begin(); it!=nodo2archi.end(); it++){
vector<prmEdge> appo;
prmNode n;
n=(*it).first;
int indice=n.getIndex();
if (indice==f || indice==t){
appo.clear();
vector<prmEdge> incArchi;
incArchi=(*it).second;
appo=(incArchi);
appo.push_back(e);
nodo2archi.erase(it);
nodo2archi.insert(make_pair(n,appo) );
}
}
return true;
}
The problem is that for the first 40-50 iterations everything go weel and the map is updated well, while with more iterations it goes sometimes in segmentation fault, sometimes in an infinite idle. I don't know why. Somebody can help me please??
Thank you very much.
You are iterating through nodo2archi and at the sametime changing its size by doing nodo2archi.erase(it); and nodo2archi.insert(make_pair(n,appo) );. If you do that your iterator may become invalid and your it++ might crash.
Are you simply trying to append data to some of the mapped vectors? In this case you don't need to erase and insert anything:
for (MapType::iterator it = map.begin(); it != map.end(); ++it) {
if (some_condition) {
it->second.push_back(some_value);
}
}
The problem is that after erasing the iterator it you are trying to perform operations on it (increment) which is Undefined Behavior. Some of the answers state that modifying the container while you are iterating over it is UB, which is not true, but you must know when your iterators become invalidated.
For sequence containers, the erase operation will return a new valid iterator into the next element in the container, so this would be a correct and idiomatic way of erasing from such a container:
for ( SequenceContainer::iterator it = c.begin(); it != c.end(); )
// note: no iterator increment here
// note: no caching of the end iterator
{
if ( condition(*it) ) {
it = c.erase(it);
} else {
++it;
}
}
But sadly enough, in the current standard, associative containers erase does not return an iterator (this is fixed in the new standard draft), so you must manually fake it
for ( AssociativeContainer::iterator it = c.begin(); it != c.end(); )
// again, no increment in the loop and no caching of the end iterator
{
if ( condition(*it) ) {
AssociativeContainer::iterator del = it++; // increment while still valid
c.erase(del); // erase previous position
} else {
++it;
}
}
And even more sadly, the second approach, correct for associative containers, is not valid for some sequence containers (std::vector in particular), so there is no single solution for the problem and you must know what you are iterating over. At least until the next standard is published and compilers catch up.
Yo do modify collection while iterating over it.
You are erasing nodes while iterating through your map. This is asking for trouble :)
You must not modify a collection itself while iterating over it. C++ will allow it, but it still results in undefined behavior. Other languages like Java have fail-fast iterators that immediately break when the collection has been modified.

Removal of elements during iteration through a list - safety

I was wondering if something like this is safe...
// Iterating through a <list>
while ( iter != seq.end()) {
if ( test ) {
iter = seq.erase( iter );
} else {
++iter;
}
I know that iterating through a vector in this way would invalidate the iterator, but would the same thing occur in a list? I assume not since a list is sequential through pointers rather than being "next" to each other in memory, but any reassurance would be helpful.
This is just fine because the erase method returns a new valid iterator.
Yes -- std::list::erase(): "Invalidates only the iterators and references to the erased elements."
That said, you probably shouldn't do this at all -- you seem to be trying to imitate std::remove_if().
The standard defines erase behaviour for every STL container. For std::list only iterators to the erased elements are invalidated. The return value of erase needn't be a dereferencable one, though (it could be list.end()).
Therefore, to erase all elements in a list the following is absolutely valid:
.. it = l.begin();
while(it != l.end()) {
it = l.erase(it);
}
BUT beware of something like this (dangerous pitfall):
for (.. it = l.begin; it != l.end(); ++it) {
it = l.erase(it);
}
If it is l.end(), it is incremented twice (second time by the loop head). Baamm.
Yes, this is the standard way to do that. See Effective STL, Item 9 (p. 46).
Yes, this is totally safe. The erase() function returns an iterator to the element succeeding the one which was erased. Had you not reassigned the result of erase() to iter, you'd have trouble.
As others have explained, your code does not invalidate the iterator used in the function. However, it does invalidate other iterators if the collection is a vector, but not if the collection is a list.
As others have mentioned, yes, it will work. But I'd recommend using list::remove_if instead, as it's more expressive.

Can I continue to use an iterator after an item has been deleted from std::multimap<>? [duplicate]

This question already has answers here:
What happens if you call erase() on a map element while iterating from begin to end?
(3 answers)
Closed 8 years ago.
Can I continue to use an multimap iterator even after a call to multimap::erase()? For example:
Blah::iterator iter;
for ( iter = mm.begin();
iter != mm.end();
iter ++ )
{
if ( iter->second == something )
{
mm.erase( iter );
}
}
Should this be expected to run correctly, or is the iterator invalidated following the call to erase? Reference sites like http://www.cplusplus.com/reference/stl/multimap/erase.html are strangely quiet on this topic of the lifespans of iterators, or the effects of constructive/destructive methods on iterators.
http://www.sgi.com/tech/stl/Multimap.html
Multimap has the important property that inserting a new element
into a multimap does not invalidate iterators that point to existing
elements. Erasing an element from a multimap also does not invalidate
any iterators, except, of course, for iterators that actually point to
the element that is being erased.
So it should look like this:
Blah::iterator iter;
for ( iter = mm.begin();iter != mm.end();)
{
if ( iter->second == something )
{
mm.erase( iter++ );
// Use post increment. This increments the iterator but
// returns a copy of the original iterator to be used by
// the erase method
}
else
{
++iter; // Use Pre Increment for efficiency.
}
}
Also see:
What happens if you call erase() on a map element while iterating from begin to end?
and
delete a specific entry in the map,but the iterator must point to the next element after the deletion
C++ Standard 23.1.2.8:
The insert members shall not affect the validity of iterators and references to the container, and the erase members shall
invalidate only iterators and references to the erased elements.
This is a common requirement for all associative containers, and std::multimap is one of them.

How do you iterate backwards through an STL list?

I'm writing some cross-platform code between Windows and Mac.
If list::end() "returns an iterator that addresses the location succeeding the last element in a list" and can be checked when traversing a list forward, what is the best way to traverse backwards?
This code workson the Mac but not on Windows (can't decrement beyond first element):
list<DVFGfxObj*>::iterator iter = m_Objs.end();
for (iter--; iter!=m_Objs.end(); iter--)// By accident discovered that the iterator is circular ?
{
}
this works on Windows:
list<DVFGfxObj*>::iterator iter = m_Objs.end();
do{
iter--;
} while (*iter != *m_Objs.begin());
Is there another way to traverse backward that could be implemented in a for loop?
Use reverse_iterator instead of iterator.
Use rbegin() & rend() instead of begin() & end().
Another possibility, if you like using the BOOST_FOREACH macro is to use the BOOST_REVERSE_FOREACH macro introduced in Boost 1.36.0.
The best/easiest way to reverse iterate a list is (as already stated) to use reverse iterators rbegin/rend.
However, I did want to mention that reverse iterators are implemented storing the "current" iterator position off-by-one (at least on the GNU implementation of the standard library).
This is done to simplify the implementation, in order for the range in reverse to have the same semantics as a range forward [begin, end) and [rbegin, rend)
What this means is that dereferencing an iterator involves creating a new temporary, and then decrementing it, each and every time:
reference
operator*() const
{
_Iterator __tmp = current;
return *--__tmp;
}
Thus, dereferencing a reverse_iterator is slower than an normal iterator.
However, You can instead use the regular bidirectional iterators to simulate reverse iteration yourself, avoiding this overhead:
for ( iterator current = end() ; current != begin() ; /* Do nothing */ )
{
--current; // Unfortunately, you now need this here
/* Do work */
cout << *current << endl;
}
Testing showed this solution to be ~5 times faster for each dereference used in the body of the loop.
Note: Testing was not done with the code above, as that std::cout would have been the bottleneck.
Also Note: the 'wall clock time' difference was ~5 seconds with a std::list size of 10 million elements. So, realistically, unless the size of your data is that large, just stick to rbegin() rend()!
You probably want the reverse iterators. From memory:
list<DVFGfxObj*>::reverse_iterator iter = m_Objs.rbegin();
for( ; iter != m_Objs.rend(); ++iter)
{
}
As already mentioned by Ferruccio, use reverse_iterator:
for (std::list<int>::reverse_iterator i = s.rbegin(); i != s.rend(); ++i)
This should work:
list<DVFGfxObj*>::reverse_iterator iter = m_Objs.rbegin();
for (; iter!= m_Objs.rend(); iter++)
{
}