[英]Stack implementation in c++ with no maximum stack size limit
我想在C ++中實現一個堆棧,該堆棧的堆棧大小沒有任何最大限制。
#include<bits/stdc++.h>
using namespace std;
#define MAX 1000
class Stack
{
int top;
public:
int a[MAX]; //Maximum size of Stack
Stack() { top = -1; }
bool push(int x);
int pop();
bool isEmpty();
};
有什么方法可以使每次創建對象時MAX取不同的值?
簡單(顯而易見)的答案是使用std::vector
。 然后,您的堆棧將無限增長,因此根本不需要MAX
。
如果出於某種原因不允許std::vector
則另一個選擇是使用模板
template <int MAX>
class Stack
{
int top;
public:
int a[MAX]; //Maximum size of Stack
Stack() { top = -1; }
bool push(int x);
int pop();
bool isEmpty();
};
在此解決方案中, MAX
是編譯時間常數。 即可以
Stack<10> s;
但這不是
int size = ...;
Stack<size> s;
最終(也是最糟糕的)解決方案是使用new
和delete
進行動態內存分配。 除非被明確禁止,否則應首選std::vector
而不是動態內存分配。
順便說一句這是一個非常糟糕的主意,使你的籌碼公眾的元素,你有做過a
以上。
使用std::vector
解決方案:
在這種實現中,堆棧實際上沒有限制。 您可以在構造函數中傳遞提示大小,只是為了預分配一些空間,以便更快地填充堆棧。 但是,如果超出此限制, std::vector
將自動增加其存儲量:
#include <cassert>
#include <vector>
class Stack
{
std::vector<int> stack;
public:
Stack(std::size_t size = 1000) {
// reserving the underlying storage space makes the stack faster
// to fill because no memory reallocation is neeeded
// for the 'size' first elements.
stack.reserve(size);
}
// doesn't return a bool anymore because every push is supposed to succeed
// (or fail with an exception if no more memory is available)
void push(int x) {
// 'stack' will grow the underlying storage space if needed
stack.push_back(x);
}
int pop() {
assert(!stack.empty());
auto res = stack.back();
stack.pop_back();
return res;
}
bool isEmpty() {
return stack.empty();
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.