c++ - 为什么不支持容器适配器中元素的初始化和迭代

标签 c++

我正在尝试使用 initializer_list<> 初始化堆栈/队列中的元素并使用迭代器迭代元素,但两者均不受支持。我知道它们是适配器并使用容器实现,但为什么我们不能执行这些操作? 只能通过 push() 将元素插入这些采用者中,并且可以使用 top()/pop()/front()/back() 方法打印/迭代元素吗?

#include <iostream>
#include <vector>
#include <queue> 
#include <stack>
#include <initializer_list>
using namespace std;
int main() 
{

 //queue<int> q1{3,4,5,6}; // COMPILATION ERROR
 //stack<int> s1{5,6,7,8};// COMPILATION ERROR

 stack<int> s1;
 s1.push(3);
 s1.push(4);
 s1.push(5);
 s1.push(6);

 //for(auto it: s1) //  COMPILATION ERROR
 //  cout << it <<" ";
 while(!s1.empty())
 {
    cout << s1.top() <<" ";
    s1.pop();
 }
} 

最佳答案

std::stackstd::queue 容器适配器大概被设计为尽可能通用。这些模板不“理解”如何存储和检索它们的元素。

堆栈需要back()push_back()pop_back() 操作。队列需要 front()back()push_back()pop_front()。因此,当您将元素插入队列时,它会在底层容器上调用 push_back(),依此类推。

为了让栈和队列支持迭代,它们必须要求底层容器也支持迭代。因此,如果你发明了一个支持front()back()push_front()push_back()pop_front()pop_back(),但不是迭代,您不能使用该容器来构造堆栈或队列。因此,堆栈和队列适配器不会尽可能通用。

希望这个回答对您有所帮助。

关于c++ - 为什么不支持容器适配器中元素的初始化和迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49528928/

相关文章:

c++ - 条件等待开销

c++ - 隐式模板方法实例化

c++ - Mel-filterbank系数的计算公式

c++ - 使用父类c++中的子方法

c++ - vc6到vs2010移植错误

javascript - QML 报告 ReferenceError : XYZ is not defined on C++ object added to context

Android - 崩溃后文件为空

c++函数返回一个枚举?

C++:unordered_map,迭代器不可比较

c++ - 将 Keras 模型转换为 TensorFlow protobuf