【问题标题】:internal implementation of stl stack and queuesstl栈和队列的内部实现
【发布时间】:2014-08-15 15:54:32
【问题描述】:

我正在使用 stl 堆栈和队列来存储大量项目。标准模板库中的堆栈是如何在内部实现的?是链表的形式吗?或者有没有给它任何最大尺寸?

【问题讨论】:

  • std::stack 默认使用std::dequelooking at some documentation 没什么问题。
  • 或者直接看实现,因为STL大多写在头文件中。

标签: c++ stl


【解决方案1】:

C++ 标准库中的堆栈和队列都是容器适配器。这意味着他们使用指定的容器作为存储数据的底层手段。默认情况下,它们都使用std::deque,但您可以使用例如向量与

std::stack<int,std::vector<int>> s;

【讨论】:

    【解决方案2】:
    vector works internally...
    
    
    #include <iostream>
    #include <vector>
    
    struct Sample
    {
        Sample(){}
        Sample(const Sample & obj)
        {
            std::cout<<"Sample copy constructor"<<std::endl;
        }
    };
    int main()
    {
        std::vector<Sample> vecOfInts;
    
        std::cout<<"Capacity :: "<<vecOfInts.capacity()<<std::endl;
        std::cout<<"Size :: "<<vecOfInts.size()<<std::endl;
        int capcity = vecOfInts.capacity();
        for(int i = 0; i < capcity + 1; i++)
            vecOfInts.push_back(Sample());
    
        std::cout<<"Capacity :: "<<vecOfInts.capacity()<<std::endl;
            std::cout<<"Size :: "<<vecOfInts.size()<<std::endl;
    
        for(int i = 0; i < capcity + 1; i++)
                vecOfInts.push_back(Sample());
    
        std::cout<<"Capacity :: "<<vecOfInts.capacity()<<std::endl;
        std::cout<<"Size :: "<<vecOfInts.size()<<std::endl;
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-09
      • 2020-08-24
      • 2013-03-21
      • 2015-10-03
      • 2016-05-01
      • 2015-05-15
      • 2021-10-06
      • 2021-07-08
      • 2014-08-12
      相关资源
      最近更新 更多