-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathStack_array.hpp
More file actions
86 lines (68 loc) · 1.69 KB
/
Stack_array.hpp
File metadata and controls
86 lines (68 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#ifndef STACK_ARRAY_HPP
#define STACK_ARRAY_HPP
#include <iostream>
#include <stdexcept>
template <typename T>
class StackA{
private:
T* data_;
size_t size_{ 0 };
size_t capacity_;
void resize(size_t nueva_capacidad)
{
T* nuevo_data = new T[nueva_capacidad];
for (size_t i = 0; i < size_; ++i) {
nuevo_data[i] = data_[i];
}
delete[] data_;
data_ = nuevo_data;
capacity_ = nueva_capacidad;
}
public:
StackA() : data_(new T[1]), capacity_(1) {}
~StackA() {
clear();
}
bool empty() const{
return size_ == 0;
}
size_t size() const{
return size_;
}
void clear(){
size_ = 0;
}
void push(const T& value) {
if (size_ == capacity_) {
resize(capacity_ * 2); // Duplica la capacidad si está llena
}
data_[size_++] = value; // Insertar el valor y aumentar el tamaño
}
// Inserta un nuevo elemento (paso por referencia rvalue)
void push(T&& value) {
if (size_ == capacity_) {
resize(capacity_ * 2); // Duplica la capacidad si está llena
}
data_[size_++] = std::move(value); // Insertar usando std::move
}
void pop(){
if (empty()) {
throw std::out_of_range("La pila esta vacia");
}
--size_;
}
T& top(){
if (empty()) {
throw std::out_of_range("La pila esta vacia");
}
return data_[size_ - 1];
}
const T& top() const
{
if (empty()) {
throw std::out_of_range("La pila esta vacia");
}
return data_[size_ - 1];
}
};
#endif