STL学习(5):stack

STL学习网址:

在数据结构中,栈是一种先入后出的容器,增加元素叫压栈或者入栈。移除元素通常叫做出栈。

STL提供的stack容器,也是这种基本类型。这里我们演示一下基本元素类型和复杂元素类型。

  • stack<int> s;
  • s.push(x)      无返回值,将元素x压栈
  • s.pop();       退栈,无返回值
  • s.top();        取栈顶元素,返回栈顶元素
  • s.empty();     判断栈是否为空,如果是空,返回1,否则返回0
  • s.size();      返回栈中元素的个数
std::vector<int> data(100, 99);// Contains 100 elements initialized to 99
data.clear(); // Remove all elements

第一条语句创建了一个有 100 个 int 型元素的 vector 对象,它的大小和容量都是 100;所有元素的初始值都是 99。第二条语句移除了所有的元素,因此大小变为 0,因为这个操作并没有改变容器的容量,所以容量还是 100。

 

简单实例代码:

查找一维有序数组

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <vector>
#include <stack>
#include <list>
#include <algorithm>
#include <time.h>
using namespace std;

int main(int argc, const char * argv[]) {

    vector<int> my_list1(10);

    srand((unsigned int) time(NULL));
    for(int i = 0; i < my_list1.size(); i++)
    {
        my_list1[i] = rand() % 100;
    }
    cout<<"aaaaa"<<endl;
    sort(my_list1.begin(), my_list1.end());

    stack<int> my_stack;

    int low;
    int hight;
    int mid;
    int test;
    my_stack.push(0);
    my_stack.push(my_list1.size() - 1);

    for(int i = 0; i < my_list1.size(); i++)
    {
        cout<<i<<":"<< my_list1[i] <<endl;
    }
    cout<<"input"<<endl;
    cin>>test;

    while (!my_stack.empty()) {
        hight = my_stack.top();//取数
        my_stack.pop();  //出来
        low   = my_stack.top();
        my_stack.pop();
        mid   = (hight + low) / 2;
        cout<<low<<" "<<hight<<endl;
        if (test == my_list1[mid]) {
            cout<< mid <<endl;
            break;
        }else if (test < my_list1[mid]) hight = mid - 1;
         else                           low   = mid + 1;
        if (low < hight) {
            my_stack.push(low);
            my_stack.push(hight);
        }
    }
    return 0;
}

基础数据类型的stack

#include <stdio.h>
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
int main(void )
{
    //定义stack对象
    stack<int> s1;

    //入栈
    s1.push(1);
    s1.push(2);
    s1.push(3);
    s1.push(4);

    //打印栈顶元素,并出栈
    while (!s1.empty()) {
        //取出栈顶元素
        cout << "top = " << s1.top() << endl;
        //获取栈的大小
        cout << "size = " << s1.size() << endl;
        //出栈
        s1.pop();
    }

    return 0;
}

 复杂数据类型的stack

//定义类
class Teacher {
public:

    char name[32];
    int  age;
    void printT() {
        cout << "age = " << age << endl;
    }

};
int main(int argc, const char * argv[]) {

    Teacher t1, t2, t3;
    t1.age = 22;
    t2.age = 33;
    t3.age = 44;

    //定义栈容器
    stack<Teacher> s1;

    //入栈
    s1.push(t1);
    s1.push(t2);
    s1.push(t3);

    //出栈并打印
    while (!s1.empty()) {
        //打印栈顶元素
        Teacher tmp = s1.top();
        tmp.printT();

        //出栈
        s1.pop();
    }

    return 0;
}

容器适配器

能成为queue基本容器类Container的条件是它应当支持size,empty,push_back,pop_front,front,back方法,可对数据的两端分别进行插入、删除操作,而deque、list都具有这些函数,所以它们可成为queue的基本容器类Container;

能成为stack基本容器类Container的条件是它应当支持size,empty,push_back, pop_back,back方法,可对数据的一端进行插入、删除操作,而deque、list、vector都具有这些函数,所以它们可成为stack的基本容器类Container。

注意:vector不能作为queue的基本容器类,因为vector没有pop_front方法。

stack基本函数操作示例

#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <stack>
using namespace std;

template <class T, class Container>
void PrintStack(stack<T, Container > obj)	//堆栈遍历模板函数
{
	while(!obj.empty())
	{
		cout << obj.top() << "\t";
		obj.pop();
	}
}
void main()
{
	stack<int, vector<int> > s;	//整形堆栈
	for(int i=0; i<4; i++)
	{
		s.push(i+1);
	}
	PrintStack(s);				//4 3 2 1
	cout << endl;

	string str = "a";			//字符串堆栈
	stack<string, list<string> > t;
	for(i=0; i<4; i++)
	{
		t.push(str);
		str += "a";

	}
	PrintStack(t);				//aaaa aaa aa a
	cout << endl;

	stack<float, deque<float> > u;//符点堆栈
	for(i=0; i<4; i++)
	{
		u.push(i+1);
	}
	PrintStack(u);				//4 3 2 1
}

综合操作示例

编一个固定大小的堆栈类。

分析:标准模板库中stack中元素个数没有限制,与题意不符,那么如何既能用上stack固有功能,又能加上特有的限制呢,其实在这句话中已经体现出了具体思路:

(1)从stack派生出自己定义的堆栈类mystack。 这样,mystack类就继承了stack的固有特性;

(2)在mystack类中加入特有的功能,题意中要求限制大小,那么一方面要定义一个成员变量m_nMaxSize, 通过构造函数传入堆栈大小,并赋给m_nMaxSize;另一方面要重载push函数,如果当前堆栈元素个数小于m_nMaxSize,则把新元素压入堆栈。

#include <iostream>
#include <deque>
#include <stack>
using namespace std;

template<class T, class Container=deque<T> >
class mystack : public stack<T, Container>
{
private:
	int m_nMaxSize;		//堆栈大小
public:
	mystack(int maxsize)
	{
		m_nMaxSize = maxsize;
	}

	void push(const T &t)//重载push函数
	{
		if(size()<m_nMaxSize)	//如果堆栈元素个数小于m_nMaxSize
		{
			stack<T, Container>::push(t); //则压入堆栈
		}
		else					//否则堆栈已满
		{
			cout << "stack is fill." << "the term " << t << " is not pushed" <<endl;
		}
	}
};
void main()
{
    mystack<int,deque<int> > obj(2);  //设置堆栈大小为2
    obj.push(1);	//可以入栈  size=1
    obj.push(2);	//可以入栈  size=2
    obj.push(3);	//栈已满,不能入栈
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: C++ STL容器中的栈(stack)是一种后进先出(LIFO)的数据结构。栈的基本操作包括入栈(push)、出栈(pop)、查看栈顶元素(top)和判断栈是否为空(empty)。栈可以用数组或链表实现,但使用STL容器可以更方便地实现栈的操作。在STL中,栈是由适配器(adapter)stack实现的,可以使用push、pop、top和empty等成员函数来操作栈。栈的应用场景包括函数调用、表达式求值、括号匹配等。 ### 回答2: 栈(stack)是C++ STL(标准模板库)中的一个容器,是一个后入先出(Last In, First Out,LIFO)的数据结构。堆栈的基本操作是退栈(Pop)和入栈(Push),即在栈顶插入和删除元素。除了这两个基本操作,堆栈还提供了访问栈顶元素的方法,即Top()。 堆栈可以通过STL中的std::stack<T>来使用,其中T是元素的类型。堆栈的定义非常简单,只需要使用一个std::stack<T>对象即可。在使用之前,需要包含头文件<stack>。 堆栈的主要特性是插入和删除元素的时间复杂度为常数时间O(1),因为栈只需要在栈顶进行操作。堆栈一般用于实现递归、表达式求值、内存分配等。例如,在递归深度优先搜索中,可以使用堆栈来存储遍历的路径。 堆栈的操作非常简单,以下是常用的操作列表: 1. push():将一个元素插入栈顶。 2. pop():删除栈顶元素。 3. top():返回栈顶元素。 4. empty():判断堆栈是否为空。 5. size():返回堆栈中元素的个数。 下面是一个简单的堆栈的例子,可以更好地理解堆栈的基本操作: #include <iostream> #include <stack> using namespace std; int main() { stack<int> s; // 定义一个int类型的栈 s.push(10); // 将10入栈 s.push(20); // 将20入栈 s.push(30); // 将30入栈 while (!s.empty()) { cout << s.top() << " "; // 输出栈顶元素 s.pop(); // 删除栈顶元素 } return 0; } 在上面的例子中,我们首先定义了一个堆栈s,然后在堆栈s中依次插入了三个元素10、20和30。接下来使用while循环,栈顶元素依次输出,同时删除栈顶元素,直到堆栈为空。由于堆栈是后进先出的,所以输出的顺序是30、20和10。 总之,堆栈是一个非常常用的数据结构,STL中的栈(stack)提供了非常方便的使用,可以减轻我们对堆栈数据结构进行操作的负担,提高代码的可读性和复用性。 ### 回答3: 栈(stack)是 C++ STL(Standard Template Library)中常见的一种容器数据结构,它可以在一端进行元素的插入和删除操作,遵循“后进先出”(LIFO,Last-In-First-Out)的原则。栈的操作不需要访问元素中间的部分,只需要在栈顶执行操作,保证了操作效率。栈可以用数组或链表等数据结构实现,但 C++ STL 提供了封装好的栈容器,使用起来方便且安全。 C++ STL 中栈容器的定义方式为:`std::stack`。栈默认情况下使用双端队列(deque)实现,用户也可以指定其他底层容器,如 vector、list 等。可以使用`push()`向栈顶插入元素,使用`pop()`弹出栈顶元素,使用`top()`获取栈顶元素。栈的元素个数可以使用`size()`来获取,判断栈是否为空可以使用`empty()`,在栈容器中查找某个元素的功能则不支持。 在实际应用中,栈容器可以用来实现函数的递归调用、表达式求值、括号匹配等操作。例如,可以使用栈来判断一个字符串中的括号是否匹配,具体做法是将左括号入栈,遇到右括号时弹出栈顶元素检查是否为相应的左括号。如果不匹配或者栈已经为空,则括号不匹配;如果字符串中所有的括号都匹配,则最后栈为空。 总之,栈作为一种容器数据结构,在实际应用中有着广泛的应用场景,C++ STL 提供的封装好的栈容器,具有使用方便、效率高等特点,可以帮助我们更快更方便地实现各种数据处理和算法设计。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值