我在制作自己的动态 vector 类时遇到了问题... 最终目标是模拟堆栈和队列,类在 vector 类上,然后迁移以在链表上创建堆栈和队列,在 C++ 上, 但是我在制作 vector 类时遇到了问题......
因为我不能创建一个具有默认值的变量,我在构造函数上分配它们,但是,它似乎不起作用,这样......我真的不想使用标准库的 有任何想法吗?
我的想法是在构造函数中声明数组,然后将其复制到类上声明的指针,但它确实有效...我只能获取第一个元素的值,而不能获取其余元素...
class Vector{
private:
int *arr;
int size;
int inside;
public:
Vector(int);
int length(); // Largo del Arreglo
int count(); // Numero de elementros adentro
bool empty(); // Vacio
bool full(); // Lleno
int at(int); // Revisa el N elemento
int get(int); // Regresa el n elemento
bool put(int, int); // Inserta elemento X en n posicicion
void clean();
};
/// Clase Vector
Vector::Vector(int x){ // Constructor
int vec[x];
arr=vec;
size=x;
inside=0;
}
// Estado del Vector
bool Vector::empty(){
if(inside==0){
return true;
}
return false;
}
bool Vector::full(){
if(inside==size){
return true;
}
return false;
}
int Vector::length(){
return size;
}
int Vector::count(){
return inside;
}
// Manipulacion de Datos
int Vector::get(int x){
int y=at(x);
put(0,x);
inside = inside-2;
return y;
}
int Vector::at(int n){
int i=arr[n];
return i;
}
bool Vector::put(int x, int p){
arr[p]=x;
inside++;
return true;
}
void Vector::clean(){
for(int i=0;i<length();i++){
put(0,i);
}
}
最佳答案
这是行不通的:
int vec[x];
arr=vec;
您正在为一个成员变量分配一个自动局部变量的地址,该变量将在函数退出时离开作用域。从那时起访问它是未定义的行为。更糟糕的是,这甚至不可移植,因为它依赖于可变长度数组的编译器扩展,这是 C++ 标准不支持的东西。
您需要使用 operator new []
动态分配您的基本 vector 从那之后您还需要正确地实现一个析构函数、赋值运算符和一个复制构造函数(如果要全面考虑,移动分配和移动构造)以正确遵守Rule of Three/Five语义。
关于c++ - 拥有 "Dynamic" vector 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22279822/