温馨提示×

C++ queue遍历的技巧有哪些

c++
小樊
84
2024-06-26 10:29:46
栏目: 编程语言

在C++中,可以使用以下几种方法来遍历一个queue:

  1. 使用循环结构和queue的成员函数:
queue<int> q;
// 添加元素到queue中
q.push(1);
q.push(2);
q.push(3);

// 遍历queue
while (!q.empty()) {
    int front = q.front();
    q.pop();
    // 处理front
}
  1. 使用STL算法中的for_each函数:
queue<int> q;
q.push(1);
q.push(2);
q.push(3);

// 遍历queue
for_each(q.c.begin(), q.c.end(), [](int& element) {
    // 处理element
});
  1. 转存为vector后遍历:
queue<int> q;
q.push(1);
q.push(2);
q.push(3);

// 转存为vector
vector<int> v;
while(!q.empty()) {
    v.push_back(q.front());
    q.pop();
}

// 遍历vector
for (int i = 0; i < v.size(); ++i) {
    int element = v[i];
    // 处理element
}

这些是一些常用的遍历queue的方法,开发者可以根据具体需求选择合适的方法。

0