开发者

Phantom Bugs using Queue (STL Library), Windows/MingW/G++

I'm having two unexpected problems using Queue from the STL Library:

1) I'm trying to clear a Queue (Queue does not have a function clear), but the intuitive way is giving me a CORE DUMP:

//The queue is defined Globally but the problem happens even
//if i define it locally and pass it by reference.
queue<pair<int,int> > Q;

void yadayada ()
{
    //initialize Q
    while (!Q.empty())
        Q.pop();   //CORE DUMP, what the hell?
}

2) When i print the element(a pair) from the queue front it is wrongly printed as (0,0). But when i use the element (returning the second element of the pair) it is right!

int yadayada2(...) 
{
//code...code...code

//the element in front is (4,20)
front = Q.front(); Q.pop();

cout << "(" &l开发者_StackOverflow社区t;< front.first << "," << front.second << ")" << endl;
//prints: (0,0) 
//what the hell?

//correctly returns 20
return front.second;
}

int main()
{
//code...code...code 

//prints 20!
cout << yadayada2 << endl;
}

I though: "Maybe the pop invalidates the element (does not make sense but...) so i moved the Q.pop(); to just before the return. But the same thing still happens...


The best way to clear a queue is:

Q = queue< pair< int, int > >(); // assign value of an empty temporary

As for the front bug, I have to agree with Oli and suspect that there is an invalid reference.


On the WTF:

  • either your code is subtle more wrong in real life (todo with replacing int with something else, such as involving auto_ptr, classes without proper copy/assignment semantics etc?)

  • OR: your mingw setup is borked.

I just cmpiled both snippets using g++ on linux AND i586-mingw32msvc-g++ AND ran it under wine AND valgrind... no problems :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜