#Creating Constructors for Stack implemented via a Vector
13 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
public:
using value_type = T;
vector<value_type> vec;
/**
* @brief Construct a new stack_vector object
*
*/
stack_vector() {
this->vec = vector<T>();
}
/**
* @brief Copy construct a stack_vector
*
*/
stack_vector(const stack_vector &other) {
this->vec = vector<T>(other);
}
/**
* @brief Copy assignment
*
*/
stack_vector &operator=(const stack_vector &other) {
vector<value_type> veccc = vector<value_type>(other);
if (this->vec != &other.vec) {
this->vec = &other.vec;
}
return this->vec;
}
/**
* @brief Destructor
*
*/
~stack_vector() {
this->vec.clear();
}
/**
* @brief Inserts element at the top
*
* @param value value to insert
*/
void push(const T &value) {
this->vec.push_back(value);
}
/**
* @brief Removes the top element
*
*/
void pop() {
this->vec.pop_back();
}
/**
* @brief Returns a reference to top element
*
* @return T&
*/
T &top() {
return this->vec.back();
}
/**
* @brief Returns the current size.
*
* @return size_t
*/
size_t size() const {
return this->vec.size();
}
private:
};
This is a text file containing the error message that i recieve
Well you are trying to convert from stack_vector<T> to std::vector<T>.
Hi, thanks! Yes I understand that they are two different structures but how would I assign the values of other to the vector? Is it possible?
You would need to write a conversion function.
It's not worth it here though. Just do the copying yourself.
@half kelp Has your question been resolved? If so, type !solved :)
What’s the point of the name alias when you keep using T?
Are you using std::vector or a different vector class template? If std::vector, then #include <vector> (and don't do "using namespace std;" in your header file)
If using std::vector, you don't need an assignment operator or copy ctor or dtor - default them (use the "rule of 0")
You have runtime errors in the pop and top - if the stack is empty you can't return a reference or pop_back the vector
check out std::stack - your interface is pretty close, but you might want to consider a few more methods and stand-alone functions: https://en.cppreference.com/w/cpp/container/stack