开发者

Trouble with iterating through std::set (c++)

I am having problems with sets all day. Some I can solve, others not. This one is bugging me since the morning, and I have run out of patience. Please help, mighty stackoverflow!

So, I have a set which contains a custom object of mine, its called "vect" and is based on eigen::matrix. That means, I get values from vects w开发者_开发问答ith the [] operator.

set<vect*> *tvps=getTheSet();

for (set<vect*>::iterator iter = tvps->begin(); iter != tvps->end(); ++iter)
{
    vect v= **iter;   // Don't really know why two asterisks,
                      // but my compiler would complain
    int x=v[0];
    int y=v[1];
    doStuffWith( v[0],v[1]);

}

Now, this will compile and run and everything. But the values I get from the iterator are 30% trash:

x: 110   y: 90
x: 230   y: 130
x: 250   y: 100
x: 230   y: 130
x: 110   y: 290
x: 140   y: 260
x: 180   y: 280
x: 150   y: 210
x: -2147483648   y: 0
x: 180   y: 280
x: 170   y: 230
x: 240   y: 270
x: -2147483648   y: 0
x: -429917536   y: 0
x: 0   y: -2147483648

I checked at the point where the set was put together which values where put in. Only the ones between 10 and 300.. as intended. How comes I find others in it? Did I screw up with the iterator?


There are a few possibilities as to why this is happening to you:

  • Are you reusing the set. If yes, do you clear() it between reuses ?
  • You are storing pointers to vectors in the set, are you changing the vectors inside the set ?

Perhaps you want to store the pointer to the vector because otherwise the compiler gives you an error due to the fact that it doesn't know how to compare two vectors. Why don't you try to implement the comparison function and store vectors directly ? that way your work would be a lot easier and much less error prone.

Also the problem you have now is that the elements in the set don't seem to be ordered.. in fact they are ordered by the pointer value, and not by X and Y (and I suppose that's what you want)


You have a set of pointers to vectors. In **iter first you dereference iterator, then pointer laying inside.

Keeping pointers can also be causing your problem: if you freed or forgot to initialize some of them, result would be rubbish.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜