问题描述
||
使用STL库中的Queue时,我遇到了两个意外问题:
1)我正在尝试清除队列(队列没有清除功能),
但直观的方法是给我一个核心转储:
//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)当我从队列前面打印元素(一对)时
错误地打印为(0,0)。但是当我使用元素(返回
对的第二个元素)是对的!
int yadayada2(...)
{
//code...code...code
//the element in front is (4,20)
front = Q.front(); Q.pop();
cout << \"(\" << 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;
}
我虽然说:\“也许流行元素使元素无效(没有意义,但是...)
所以我移动了Q.pop();到返回之前。但是同样的事情仍然发生...
解决方法
清除队列的最佳方法是:
Q = queue< pair< int,int > >(); // assign value of an empty temporary
至于“ 3”错误,我必须同意奥利(Oli)并怀疑引用无效。
,在WTF上:
或者您的代码在现实生活中犯了更多的错误(用其他方法替换int,例如涉及auto_ptr,没有适当的复制/赋值语义的类等)?
或者:您的mingw设置很糟糕。
我只是在Linux和i586-mingw32msvc-g ++上使用g ++编译了两个代码片段,并在wine和valgrind下运行了它……没有问题:)