向量上push方法的C++错误

C++ error for push method on vector

本文关键字:C++ 错误 方法 push 向量      更新时间:2023-10-16

我是使用c++的新手,所以请原谅我。我正在尝试实现一个推送函数,在Template Vector的末尾添加一个项。尽管我正在使用与Vector相关的push_back函数,但我收到了一条无法解释的错误消息。

更新:我知道在头文件中实现函数是不合适的,但这就是为我设置项目的方式,我需要让它运行。下面的代码用于"stack_vec_tpt.h"

我希望这能让事情稍微明朗一点。

以下是正在使用的头文件的代码:

#ifndef _STACK_VEC_TPT_H_
#define _STACK_VEC_TPT_H_
#include <stdexcept>
using namespace std;
// abstract stack class implemented using vector
template<class T>
class abs_stack_vec {
public:
// pushes an element onto the top of the stack. 
// grows the vector if needed.
virtual void push(const T& elem)=0;
// pops an element from the top of the stack.
// does nothing if the stack is empty.
virtual void pop()=0;
// returns the value of the top element on the stack.
// throws domain_error if the stack is empty.
virtual const T& top() const=0;
// returns the number of elements currently on the stack.
virtual unsigned size() const=0;
};
// the following class inherits from the abstract stack class
// using its own implementation of a vector
// you must implement the abstract methods push, pop, and top.
template<class T>
class mystack_vec: public abs_stack_vec<T> {
public:
    unsigned size() const {return _size;}
// method used for growing vector when size equals capacity
// and need to add more elements
void grow() {
    T* temp = new T[_size * 2];
    for(unsigned i = 0; i < _size; ++i) {
        temp[i] = _values[i];
    }
    delete[] _values;
    _values = temp;
    _capacity = _size * 2;
}
// default constructor
mystack_vec() {
    _capacity = 5;
    _size = 0;
    _values = new T[_capacity];
}
//destructor
~mystack_vec() {
    delete[] _values;
}
// TO-DO: YOU MUST IMPLEMENT: PUSH
void push(const T& elem) {
    mystack_vec.push_back();
}
// END OF TO-DO
private:
    T *_values; // array !!
    unsigned _size, _capacity;
};
#endif

此外,我收到的错误消息如下:错误1错误C2143:语法错误:缺少";"在"."之前62号线

第62行用于void push()中的语句"mystack_vec.push_back();"。

要修复语法错误,需要告诉编译器实现属于mystack_vec:

template<typename T>
mystack_vec<T>::~mystack_vec() {
    delete[] _values;
}
template<typename T>
void mystack_vec<T>::push(const T& elem) {
    // The implementation needs to check if you have enough capacity, 
    // grow _values if necessary,
    // and store elem in the _values[_size++]
}

实现push运算符是您练习的重点。这并不难,因为你有一个工作的grow()函数。上面的评论中解释了您在实现中需要遵循的三个步骤。

mystack_vec是一种类型,而不是对象。您可以对它进行的唯一调用是针对静态函数的,这些函数将使用::而不是.。出现错误消息是因为它希望您声明一个变量或其他什么,而没有在那个位置期望.

访问提供的头文件底部的数组

`private:
    T *_values; // array !!
    unsigned _size, _capacity;
};`

然后为推送方法实现以下代码:

    void push(const T& elem) {
    if (_capacity == _size)
    {
        grow();
    }
    _values[_size] = elem;
    _size++;
}