#4 Michal
stdexcept je tam len kvoly vynimke std::logic_error.
Ak sa ti nechce implementovat vlastny stack, tak mozs pouzit adapter std::stack.
#include <stack>
#include <iostream>
int main(){
std::stack<int> stack; //alebo std::stack<int, std::vector<int>> stack;
stack.push(1);
stack.push(2);
stack.pop();
stack.push(3);
std::cout << stack.top();
}
Ja som si uz raz implementoval stack ktory pouziva polia, kludne ho mozes pouzit ak chces:
#include <iostream>
#include <algorithm>
#include <initializer_list>
#include <type_traits>
template <class T, size_t N>
class stack final{
template <typename, size_t>
friend class stack;
public:
typedef T value_type;
typedef T& reference;
typedef const value_type& const_reference;
typedef T* pointer;
typedef const T* const_pointer;
private:
char data[sizeof(value_type)*N];
size_t pos;
inline pointer t_data(size_t i){return reinterpret_cast<pointer>(data) + i;}
inline const_pointer t_data(size_t i)const{return reinterpret_cast<const_pointer>(data) + i;}
public:
stack():pos(0){}
stack(size_t n){
pos = std::min(N, n);
for(size_t i = 0; i < pos; ++i)
new(t_data(i)) value_type();
}
stack(size_t n, const_reference t){
pos = std::min(N, n);
for(size_t i = 0; i < pos; ++i)
new(t_data(i)) value_type(t);
}
template <class U, size_t M>
stack(const stack<U, M>& s){
pos = std::min(N, s.pos);
for(size_t i = 0; i < pos; ++i)
new(t_data(i)) value_type(*s.t_data(i));
}
template <class U, size_t M>
stack(stack<U, M>&& s){
pos = std::min(N, s.pos);
for(size_t i = 0; i < pos; ++i)
new(t_data(i)) value_type(std::move(*s.t_data(i)));
}
template <class I>
stack(I beg, I end){
for(pos = 0; (beg != end) && (pos < N); ++beg, ++pos)
new(t_data(pos)) value_type(*beg);
}
stack(std::initializer_list<T>&& inic_list){
auto beg = std::begin(inic_list);
auto end = std::end(inic_list);
for(pos = 0; (beg != end) && (pos < N); ++beg, ++pos)
new(t_data(pos)) value_type(std::move(*beg));
}
~stack(){
if(!std::is_trivial<value_type>::value)
for(size_t i = pos; i > 0; --i)
t_data(i-1)->~value_type();
}
void clear(){
if(!std::is_trivial<value_type>::value)
for(; pos > 0; --pos)
t_data(pos-1)->~value_type();
pos = 0;
}
size_t size()const{return pos;}
constexpr size_t max_size()const{return N;}
bool empty()const{return (pos == 0);}
bool full()const{return (pos == N);}
template <class U>
void push(const U& u){
new(t_data(pos)) value_type(u);
++pos;
}
template <class U>
void push(U&& u){
new(t_data(pos)) value_type(std::move(u));
++pos;
}
template <class... Args>
void emplace(Args... args){
new(t_data(pos)) value_type(args...);
++pos;
}
void pop(){
--pos;
t_data(pos)->~value_type();
}
const_reference top(){
return *t_data(pos-1);
}
};