I have some code that I'm updating to C++11 using gcc 4.7 (from 3.1)
I have a multiset defined as a private member of a class:
multiset <Object*, objectcomp> objects_;
In the code is a segment that looks like this (p_q is a pair of multiset iterators, sorry about that nasty line, can't wait to replace that with auto, haha):
void Terrain::removeObject(Object* obj){
pair<multiset<Object*, objectcomp>::iterator, multiset<Object*, objectcomp>::iterator> p_q;
multiset<Object*, objectcomp>::iterator p,q;
q = NULL;
p_q = objects_.equal_range(obj);
for(p = p_q.first; p != p_q.second; p++){
if(*p == obj) {q=p; break;}
}
if(q!=NULL){
... do stuff based on q no longer being null
}
}
This won't compile anymore. Can you not set iterators to null anymore? What is the alternative? (nullptr doesn't work either)
It was never legal to set iterators to NULL. You may have gotten lucky because your particular implementation happened to use pointers as iterators for that type, but it was still illegal.
The right answer is:
q = objects_.end();
Or, in some cases:
q = multiset<Object*, objectcomp>::iterator();
You never could set an iterator to NULL. If the above code ever worked, it was by sheer accident. Given any reasonable implementation of multiset, it's hard to see how it could ever have compiled, let alone run.
The best way to get a "nowhere" iterator is to use the end of the container. Replace q = NULL with q = objects_.end().
Also, never put raw pointers in a container; it's an open invitation to memory leaks. You almost certainly want either multiset<Object,comp> or multiset<shared_ptr<Object>,comp>.
Related
I have been struggling to put a vector object into a project im doing
I have read what little i could find about doing this and decided to give it a go.
std::vector<BrickFalling> fell;
BrickFalling *f1;
I created the vector. This next piece works fine until i get to the erase
section.
if(brickFall == true){
f1 = new BrickFalling;
f1->getBrickXY(brickfallx,brickfally);
fell.push_back(*f1);
brickFall = false;
}
// Now setup an iterator loop through the vector
vector<BrickFalling>::iterator it;
for( it = fell.begin(); it != fell.end(); ++it ) {
// For each BrickFalling, print out their info
it->printBrickFallingInfo(brick,window,deadBrick);
//This is the part im doing wrong /////
if(deadBrick == true)// if dead brick erase
{
BrickFalling[it].erase;//not sure what im supposed to be doing here
deadBrick = false;
}
}
You can totally avoid the issue by using std::remove_if along with vector::erase.
auto it =
std::remove_if(fell.begin(), fell.end(), [&](BrickFalling& b)
{ bool deadBrick = false;
b.printBrickFallingInfo(brick,window,deadBrick);
return deadBrick; });
fell.erase(it, fell.end());
This avoids the hand-writing of the loop.
In general, you should strive to write erasure loops for sequence containers in this fashion. The reason is that it is very easy to get into the "invalid iterator" scenario when writing the loop yourself, i.e. not remembering to reseat your looping iterator each time an erase is done.
The only issue with your code which I do not know about is the printBrickFallingInfo function. If it throws an exception, you may introduce a bug during the erasure process. In that case, you may want to protect the call with a try/catch block to ensure you don't leave the function block too early.
Edit:
As the comment stated, your print... function could be doing too much work just to determine if a brick is falling. If you really are attempting to print stuff and do even more things that may cause some sort of side-effect, another approach similar in nature would be to use std::stable_partition.
With std::stable_partition you can "put on hold" the erasure and just move the elements to be erased at one position in the container (either at the beginning or at the end) all without invalidating those items. That's the main difference -- with std::stable_partition, all you would be doing is move the items to be processed, but the items after movement are still valid. Not so with std::remove and std::remove_if -- moved items are just invalid and any attempt to use those items as if they are still valid is undefined behavior.
auto it =
std::stable_partition(fell.begin(), fell.end(), [&](BrickFalling& b)
{ bool deadBrick = false;
b.printBrickFallingInfo(brick,window,deadBrick);
return deadBrick; });
// if you need to do something with the moved items besides
// erasing them, you can do so. The moved items start from
// fell.begin() up to the iterator it.
//...
//...
// Now we erase the items since we're done with them
fell.erase(fell.begin(), it);
The difference here is that the items we will eventually erase will lie to the left of the partitioning iterator it, so our erase() call will remove the items starting from the beginning. In addition to that, the items are still perfectly valid entries, so you can work with them in any way you wish before you finally erase them.
The other answer detailing the use of remove_if should be used whenever possible. If, however, your situations does not allow you to write your code using remove_if, which can happen in more complicated situations, you can use the following:
You can use vector::erase with an iterator to remove the element at that spot. The iterator used is then invalidated. erase returns a new iterator that points to the next element, so you can use that iterator to continue.
What you end up with is a loop like:
for( it = fell.begin(); it != fell.end(); /* iterator updated in loop */ )
{
if (shouldDelete)
it = fell.erase(it);
else
++it;
}
I've got this piece of code:
for (std::vector<Marker>::iterator it = markers.begin(); it != markers.end(); ++it) {
if (it->getDots().size() < 3) {
markers.erase(it);
}
}
In one of test inputs (the app does image analysis) I get a segfault. I tried to debug the code (to no avail) and noticed one thing. When asking gdb to p markers.size() i receive $9 = 3. So I would expect the loop to iterate three times, but surprisingly it does it (at least) 5 times. In fifth iteration there's a segfault. What I also noticed is that it's not the dereference of *it (here it->) that causes the error. It's specifically it->getDots(), which is a simple getter.
I write in C++ very rarely, so it might be some simple mistake, but neither my debugging, nor googling brought any solution. Could you help?
I'd like to emphasize, that on various different inputs (slightly different images) this function works properly, so it's even harder for me to trace the bug down.
vector::erase invalidates all iterators pointing to the element being erased, and all elements that follow. So it becomes invalid, and ++it expression on the next loop iteration exhibits undefined behavior.
The best way to code this logic is with erase-remove idiom.
The problem is this line:
markers.erase(it);
The iterator is invalidated. But that's okay, erase returns a valid iterator:
auto it = markers.begin();
while(it != markers.end())
{
if(it->getDots().size() < 3) {
it = markers.erase(it);
}
else ++it;
}
You need to update it when you erase:
it = markers.erase(it);
since erase will "change" the vector, and your current it is no longer valid (and only do it++ if when you didn't erase it).
However, the more common way to do this is to use this type of construction:
markers.erase(std::remove(markers.begin(), markers.end(), number_in), markers.end());
I am writing a small game engine as a summer project, and am struggling a little with the STL map.
I have declared a class RenderList to hold objects. The RenderList will be passed to a Renderer class to do the work.
The RenderList has a map<std::string,Entity*> objects;
That all works, till I try to obtain an Entity* from the map and I get:
Assertion failed, in vc/include/xtree
Expression: map/set iterator not dereferencable.
This is the code to retrieve the pointer.
Entity* RenderList::getByName(std::string str){
return objects.find(str)->second;
}
I need it to hold a pointer and not the actual object, as there are different sub-classes of Entity which I'll need.
I am fairly new to the STL, should I not store pointers in a map?
Surely I should be allowed to do this, or is it a better idea to store objects instead?
And finally, am I simply doing it wrong!?
Hope this question is not a duplicate, I did do a quick search beforehand. Also if this would be better in the GameDev Stack I'll post it there.
If the key is not found then map::find(key) returns a "past-the-end" iterator, i.e. the value returned by map::end(), and that iterator doesn't point to any element so can't be dereferenced. You do not check what find returns before dereferencing it.
Are you sure they key is in the map?
You probably want to do something like return NULL if the key isn't found, which you can check for by comparing the returned iterator to end e.g.
Entity* RenderList::getByName(std::string str){
map_type::iterator it = objects.find(str);
if (it == objects.end())
return NULL;
return it->second;
}
Where RenderList defines the typedef:
typedef map<std::string,Entity*> map_type;
(N.B. I always make my classes define typedefs for the containers I use as implementation details, because it's much easier to write map_type::iterator than map<std::string,Entity*>::iterator and because if I change the container to something else I don't have to change all the code using it to e.g. map<std::string,shared_ptr<Entity>>::iterator I can just leave it as map_type::iterator and it still works perfectly.)
Regarding the general design, can you store a boost::shared_ptr<Entity> or std::tr1::shared_ptr<Entity> instead of a raw pointer? It will be much safer and simpler to manage the object lifetimes.
That probably means that the name you were looking for does not exist in the map. If the key does not exist, find method return the end iterator for the map, which is indeed not dereferencable.
If the "not found" situation is something that can naturally happen, then you can do this
Entity* RenderList::getByName(std::string str){
map<std::string,Entity*>::iterator it = objects.find(str);
return it != objects.end() ? it->second : NULL;
}
thus passing on the responsibility to handle this situation to the caller.
If the "not found" situation is not supposed to happen, either throw an exception or at least do
assert(it != objects.end());
One thing wrong with this is that you need to handle the case where the there is no entry which matches str. Not sure what the specific error is about however as I've (regrettably) done the same dip into a map to retrieve a pointer..
If the map does not contain the key you pass to the find method, then it will return objects.end(). Dereferencing this is a runtime error and will likely cause the error you see. Try instead:
map<std::string,Entity*>::iterator findIt;
findIt = objects.find(str);
if ( findIt != objects.end() )
{
return findIt->second;
}
else
{
// Handle error here
}
As others have pointed out, the name that you are looking up doesn't exist in the map. Everyone is quick to suggest that you check the return value of .find(). I suggest, instead, that you don't call .find(). Here is how I would solve your problem:
Entity* RenderList::getByName(std::string str){
return objects[str];
}
In the code above, looking up a non-existent map entry will create an entry with a NULL pointer value, and return NULL.
You need to add some code somewhere to check for a null pointer before you deference it.
This is a follow-up on a previous question I had ( Complexity of STL max_element ).
I want to basically pop the max element from a set, but I am running into problems.
Here is roughly my code:
set<Object> objectSet;
Object pop_max_element() {
Object obj = *objectSet.rbegin();
set<Object>::iterator i = objectSet.end()--; //this seems terrible
objectSet.erase(i); //*** glibc detected *** free(): invalid pointer
return obj;
}
Earlier I tried objectSet.erase(objectSet.rbegin()); but the compiler complained that there was no matching function (I'm guessing it doesn't like the reverse_iterator). I know there is no checking for an empty set, but it's failing when objectSet.size() >> 0.
You're pretty close, but you're trying to do a little too much in that iterator assignment. You're applying the post-decrement operator to whatever end returns. I'm not really sure what that does, but it's almost certainly not what you want. Assign the result of end to i, and then decrement it to get the last element of the set.
set<Object>::iterator i = objectSet.end();
--i;
Object obj = *i;
objectSet.erase(i);
return obj;
You need to do this:
set<Object> objectSet;
Object pop_max_element() {
Object obj = *objectSet.rbegin();
set<Object>::iterator i = --objectSet.end(); // NOTE: Predecrement; not postdecrement.
objectSet.erase(i); //*** glibc detected *** free(): invalid pointer
return obj;
}
The statement
set<Object>::iterator i = objectSet.end()--;
means 'assign end() to i then decrement a temporary variable that is about to be thrown away'. In other words it's the same as set<Object>::iterator i = objectSet.end();, and I'm sure you recognise you cannot erase end(), because it points to one past the end. Use something like this instead:
assert(!objectSet.empty()); // check there is something before end
set<Object>::iterator i = objectSet.end();
--i;
objectSet.erase(i);
and that's okay, it's a legitimate way to essentially reproduce .back() for a set.
Also, reverse iterators have a base() member to convert to a normal iterator and I guess you can only erase normal iterators - try objectSet.erase(objectSet.rbegin().base()).
Im holding an iterator that points to an element of a vector, and I would like to compare it to the next element of the vector.
Here is what I have
Class Point{
public:
float x,y;
}
//Somewhere in my code I do this
vector<Point> points = line.getPoints();
foo (points.begin(),points.end());
where foo is:
void foo (Vector<Point>::iterator begin,Vector<Point>::iterator end)
{
std::Vector<Point>::iterator current = begin;
for(;current!=end-1;++current)
{
std::Vector<Point>::iterator next = current + 1;
//Compare between current and next.
}
}
I thought that this would work, but current + 1 is not giving me the next element of the vector.
I though operator+ was the way to go, but doesnt seem so. Is there a workaround on this?
THanks
current + 1 is valid for random access iterators (which include vector iterators), and it is the iterator after current (i.e., what you think it does). Check (or post!) your comparison code, you're probably doing something wrong in there.
std::vector has random-access iterators. That means they are, basically, as versatile as pointers. They provide full-blown pointer arithmetic (it+5, it+=2) and comparisons other than !=/== (i.e., <, <=, >, and >=).
Comparison between iterators in your code should certainly work, but would be nonsensical:
for(std::vector<Point>::iterator current = begin;current!=end-1;++current)
{
std::vector<Point>::iterator next = current + 1;
assert(current!=next); // always true
assert(current<next); // also always true
}
So if it doesn't work for you, it's likely you do something wrong. Unfortunately, "...is not giving me the next element of the vector..." doesn't give us no clue what you are trying, so it's hard to guess what you might be doing wrong.
Maybe it's just a typo, but your code is referring to Vector while the standard container is vector (lower case V).
But if that's not a typo in your question, without seeing the definition of Vector, there's no way to tell what that does.