我创建了一个程序,它将从队列中删除输入数字的每个实例,但无法弄清楚如何修改它,以便它只删除所述数字的第一个实例。
以下是我的程序:
#include <iostream>
#include <list>
#include <stack>
#include <queue>
using namespace std;
int main(){
queue<int> q;
int size;
cout << "Enter the size of the queue: ";
cin >> size;
int val;
for (int i = 0; i < size; i++){
cout << "Enter a value to insert into the queue: ";
cin >> val;
q.push(val);
}
int value;
bool found = false;
queue<int> temp;
queue<int> printQueue;
cout << "Which value would you like to remove: ";
cin >> value;
while (!q.empty()){
if (q.front() == value)
q.pop();
else{
temp.push(q.front());
q.pop();
}
}
q = temp;
printQueue = q;
while (!printQueue.empty()){
cout << printQueue.front() << " ";
printQueue.pop();
}
}
我该如何修改?我正在考虑在while循环中放置一个bool值来删除所有内容,但是一旦找到它就会启动它,而不会完成将其余队列复制到临时队列中。
任何帮助都会很棒。
答案 0 :(得分:0)
如果要求允许,您可以使用双端队列,允许迭代和修改。
#include <algorithm>
#include <queue>
int value;
std::deque<int> q;
//insert numbers
//define value
//find first instance of value
auto iter = std::find(std::begin(q), std::end(q), value);
//if found, erase it
if (iter != std::end(q)) {
q.erase(iter);
}
答案 1 :(得分:0)
我认为你非常接近,你可以在你的while循环中添加一个验证来弹出你的元素一次。
int main(){
queue<int> q;
int size;
cout << "Enter the size of the queue: ";
cin >> size;
int val;
for (int i = 0; i < size; i++){
cout << "Enter a value to insert into the queue: ";
cin >> val;
q.push(val);
}
int value;
bool found = false;
queue<int> temp;
queue<int> printQueue;
cout << "Which value would you like to remove: ";
cin >> value;
while (!q.empty()){
if (q.front() == value && found == false)
q.pop();
found = true;
else{
temp.push(q.front());
q.pop();
}
}
q = temp;
printQueue = q;
while (!printQueue.empty()){
cout << printQueue.front() << " ";
printQueue.pop();
}
}