#Creating Constructors for Stack implemented via a Vector

13 messages · Page 1 of 1 (latest)

half kelp
#

Hey guys I need help implementing a Stack using a custom created vector class. Currently I am getting some errors in the process, so could anyone help?

sinful vortexBOT
#

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.

half kelp
#
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:
};
honest hatch
#

Well you are trying to convert from stack_vector<T> to std::vector<T>.

half kelp
#

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?

honest hatch
#

You would need to write a conversion function.
It's not worth it here though. Just do the copying yourself.

sinful vortexBOT
#

@half kelp Has your question been resolved? If so, type !solved :)

honest solar
#

What’s the point of the name alias when you keep using T?

solemn hazel
#

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