我在运行时收到一条内存错误消息,我是 STL 的新手,所以我不确定是否 我需要以特殊方式处理队列,例如在函数中删除它们等等。
我追踪到这个函数的错误
template <typename T>
bool contains(std::queue<T> set, T val){
std::queue<T> hold;
bool isContained = false;
if (set.front() == val) isContained = true;
while(!set.empty()){
hold.push(set.front());
set.pop();
if (set.front() == val) isContained = true;
}
while(!hold.empty()){
set.push(hold.front());
hold.pop();
}
return isContained;
}
在我的 main() 中,我为队列成功调用了这个函数 20 次,然后在第一次在队列上调用该函数时,程序在函数的两个循环之间发出“内存故障”消息。
我正在使用 gnu 编译器。
最佳答案
在您第二次调用 set.front()
时,无法保证集合不为空。
关于模板函数 <queue> 中的 C++ 内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15425484/