1 概述
堆栈是一种容器适配器,专门设计用于在后进先出(后进先出)环境中操作,其中元素仅从容器的一端插入和提取。
堆栈被实现为容器适配器,容器适配器是使用特定容器类的封装对象作为其底层容器的类,提供一组特定的成员函数来访问其元素。元素是从特定容器的“后部”推/弹出的,即堆栈的顶部。
底层容器可以是任何标准容器类模板或某些其他专门设计的容器类。集装箱应支持以下操作:
- empty 是否为空
- size 栈大小
- back 栈顶元素
- push_back 入栈
- pop_back 出栈
标准容器类vector、deque和list满足这些要求。默认情况下,如果没有为特定堆栈类实例化指定容器类,则使用标准容器deque。
其类图如下:
2 使用实例
void StackSuite::push()
{
std::stack<int> a;
a.push(10);
TEST_ASSERT_EQUALS(10, a.top())
a.push(20);
TEST_ASSERT_EQUALS(20, a.top())
a.push(30);
TEST_ASSERT_EQUALS(30, a.top())
}
void StackSuite::pop()
{
std::stack<int> a(std::deque<int>({ 10, 20, 30 }));
TEST_ASSERT_EQUALS(30, a.top())
a.pop();
TEST_ASSERT_EQUALS(20, a.top())
a.pop();
TEST_ASSERT_EQUALS(10, a.top())
if(!a.empty())
a.pop();
TEST_ASSERT_EQUALS(true, a.empty())
}
3 接口使用
3.1 construct
std::stack<int> getStack(int size, int value)
{
return std::stack<int>(std::deque<int>(size, value));
}
void StackSuite::construct()
{
std::deque<int> de(3, 100);
std::vector<int> v(2, 200);
std::stack<int> a;
std::stack<int> b(de);
std::stack<int, std::vector<int>> c;
std::stack<int, std::vector<int>> d(v);
std::stack<int> e(b);
std::stack<int> f(getStack(4, 5));
TEST_ASSERT_EQUALS(0, a.size())
TEST_ASSERT_EQUALS(3, b.size())
TEST_ASSERT_EQUALS(0, c.size())
TEST_ASSERT_EQUALS(2, d.size())
TEST_ASSERT_EQUALS(3, e.size())
TEST_ASSERT_EQUALS(4, f.size())
}
说明:
- 容器类型可以是deque和vecotr,默认类型是deque
3.2 empty
void StackSuite::empty()
{
std::stack<int> a;
std::stack<int> b(getStack(4, 5));
TEST_ASSERT_EQUALS(true, a.empty())
TEST_ASSERT_EQUALS(false, b.empty())
}
3.3 size
void StackSuite::size()
{
std::stack<int> a;
std::stack<int> b(getStack(4, 5));
TEST_ASSERT_EQUALS(0, a.size())
TEST_ASSERT_EQUALS(4, b.size())
}
3.4 top
void StackSuite::top()
{
std::stack<int> a(std::deque<int>({ 10, 20, 30 }));
TEST_ASSERT_EQUALS(30, a.top())
a.top() -= 5;
TEST_ASSERT_EQUALS(25, a.top())
}
3.5 push
void StackSuite::push()
{
std::stack<int> a;
a.push(10);
TEST_ASSERT_EQUALS(10, a.top())
a.push(20);
TEST_ASSERT_EQUALS(20, a.top())
a.push(30);
TEST_ASSERT_EQUALS(30, a.top())
}
3.6 emplace
void StackSuite::emplace()
{
std::stack<std::string> a;
a.emplace("James");
TEST_ASSERT_EQUALS("James", a.top())
a.emplace("Tom");
TEST_ASSERT_EQUALS("Tom", a.top())
a.emplace("Jim");
TEST_ASSERT_EQUALS("Jim", a.top())
}
3.7 pop
void StackSuite::pop()
{
std::stack<int> a(std::deque<int>({ 10, 20, 30 }));
TEST_ASSERT_EQUALS(30, a.top())
a.pop();
TEST_ASSERT_EQUALS(20, a.top())
a.pop();
TEST_ASSERT_EQUALS(10, a.top())
if(!a.empty())
a.pop();
TEST_ASSERT_EQUALS(true, a.empty())
}
3.8 swap
void StackSuite::swap()
{
std::stack<int> a;
std::stack<int> b(getStack(4, 5));
TEST_ASSERT_EQUALS(0, a.size())
TEST_ASSERT_EQUALS(4, b.size())
a.swap(b);
TEST_ASSERT_EQUALS(4, a.size())
TEST_ASSERT_EQUALS(0, b.size())
}