STL堆栈和队列的内部实现

7

我正在使用STL的栈和队列来存储大量的项目。标准模板库中的堆栈是如何实现的?它是以链表的形式实现的吗?还是有任何给定的最大大小?


5
默认情况下,std::stack 使用 std::deque。查看一些文档并没有问题。 - juanchopanza
或者直接查看实现,因为STL大多数是写在头文件中的。 - Remy Lebeau
2个回答

9

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

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

-3
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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接