类似栈的后进先出,但需要能用方括号[]遍历元素,可以用下标访问到元素。最终效果类似arr[0]是获取到当前数组最后一个元素的值,arr[1]获取到倒数第二个元素。如果用vector的insert方法插入到容器的第0个位置,好像可以,但这效率太低了,每次插入后得重排。所以想问下有没有更好的办法,谢谢先
不论是用vector还是自定义数组,想要无限动态扩容,一定免不了heap allocation和大量数据的拷贝操作,效率极低;
我推荐使用链表来模拟栈;虽然链表没法random access,但通过重载[]运算符可以模拟这个效果。
如果你需要代码我可以帮你实现一下(¯︶¯)
代码如下:(点个采纳吧,球球了!QAQ~)
#include <iostream>
#include <list>
template<typename T>
class Stack
{
public:
// default ctor
Stack() = default;
// push element into the stack
void push(const T& __ele) noexcept
{
this->m_stack.push_back(__ele);
}
// pop element out the stack
void pop() noexcept
{
this->m_stack.pop_back();
}
// get the top element
T& top() noexcept
{
return *this->m_stack.rbegin();
}
// check if the stack is empty
bool is_empty() const noexcept
{
return this->m_stack.empty();
}
// get the size of stack
unsigned int size() const noexcept
{
return this->m_stack.size();
}
// overload operator[] to random access
T& operator[] (const unsigned int idx)
try
{
if(idx >= this->size())
throw std::domain_error("Index out of range! \n");
auto iter = this->m_stack.begin();
for(int i = 0; i < idx; i++, iter++);
return *iter;
}
catch(const std::domain_error& e)
{
std::cout << e.what() << '\n';
throw;
}
private:
std::list<T> m_stack;
};
#define TEST
#ifdef TEST
int main()
{
Stack<int> stack;
for (int i = 0; i < 10; i++)
stack.push(i);
// access top
std::cout << stack.top() << '\n';
// pop top
stack.pop();
// access top
std::cout << stack.top() << '\n';
// access with []
std::cout << stack[0] << '\n';
// assign with []
stack[0] = 11;
std::cout << stack[0] << '\n';
// iter with []
for(int i = 0; i < stack.size(); i++)
std::cout << stack[i] << ' ';
}
#endif