此程序取自cplusplus.com
#include <iostream>
#include <vector>
#include <deque>
#include <stack>
using namespace std;
int main ()
{
deque<int> mydeque (3,100); // deque with 3 elements
vector<int> myvector (2,200); // vector with 2 elements
stack<int> first; // empty stack
stack<int> second (mydeque); // stack initialized to copy of deque
stack<int,vector<int> > third; // empty stack using vector
stack<int,vector<int> > fourth (myvector);
cout << "size of first: " << (int) first.size() << endl;
cout << "size of second: " << (int) second.size() << endl;
cout << "size of third: " << (int) third.size() << endl;
cout << "size of fourth: " << (int) fourth.size() << endl;
return 0;
}我不能理解的是,为什么我们要提到stack<int, vector<int>>,即两种数据类型,而不仅仅是stack<vector<int>>
发布于 2012-10-04 22:43:03
查看:http://www.sgi.com/tech/stl/stack.html
为模板创建一个带有两个数据类型参数的堆栈,就像stack<T, Sequence> stack;一样
这是因为第一个类型参数是堆栈保存的元素类型,第二个类型参数是用于实现堆栈的容器类型。
使用不同的容器类型会给你不同的内存分配,在速度等方面的优点和缺点,等等。它只是在你想要使用的实现类型方面给了你作为消费者更多的灵活性。
通过该链接:
堆栈是一个容器适配器,这意味着它是在一些底层容器类型之上实现的。默认情况下,基础类型是双队列,但可以显式选择不同的类型。
发布于 2012-10-05 16:58:20
重要的一点是,stack不是容器,而是容器适配器。
在C++中,容器适配器是给定容器的附加接口。适配器使用的标准容器在一般情况下工作得很好,但有时您可能希望使用不同的底层数据结构。
另请参见What are Containers/Adapters? C++。
要了解它们为什么不是容器,请查看Container Adapters do not support iterators,它举例说明了例如stack不提供迭代器。
额外的知识:模板程序员可能会问“为什么第二个参数不是模板参数,比如
template <typename T, template <typename, typename> class Seq >
struct stack {};
#include <vector>
int main () {
stack<int, std::vector> s;
}?“
快速回答:这将极大地降低适配器类的功能。
vector的完整签名是std::vector<T, Alloc=...>),因此适配器用户无法对其进行微调发布于 2012-10-05 00:32:52
这正是标准库容器模板的设计方式:第一个模板参数是所包含数据的类型(对于关联容器,前两个参数是)。
没有什么能阻止你以不同的方式设计你自己的模板,例如,如你所建议的:
template <typename Backend>
class my_stack
{
public:
typedef Backend container_type;
typedef typename container_type::value_type value_type;
private:
container_type container;
// ...
};然而,这种设计有两个缺点:
int,我必须自己考虑一个容器,我不能简单地说my_stack<int>.value_type。我不能说my_stack<my_insane_container<int>>.现在,你可以通过这样的方式来克服第二个抱怨:
template <typename> class my_crazy_stack;
template <template <typename ...> class Tmpl, typename T, typename ...Args>
class my_cazy_stack<Tmpl<T, Args...>>
{
public:
typedef Tmpl<T, Args...> container_type;
typedef T value_type;
// ...
};所以,简而言之,标准库的设计是非常明智的。
https://stackoverflow.com/questions/12729732
复制相似问题