c++将项存储到数组中

c++ store items into an array

本文关键字:数组 存储 c++      更新时间:2023-10-16

我有这个代码,在我的脑海中,它收到一个名为Vehicle的项目,它必须将其存储在一个名为Node的数组中。以下是与这部分程序相关的代码:

void Table::process(Vehicle v, int cont) {
    char a='A'+cont;
    putVehicle(a,v);
    Node.a_v[cont]=v;
    if(cont==0) a_surt=v.rowVehicle();
}

这就是我如何在Table.h的私有部分设置数组:

struct Node{
    Vehicle a_v;
};
我得到的错误是:
error: expected primary-expression before '.' token

我有我需要的包括,但每次我输入这个:Node.a_v它给我那个错误。任何建议吗?

如果你想使用一个结构体,你需要在使用它之前声明一个Node。此外,该结构体需要包含数组(或者更好的是,查看vector 以获得更大的灵活性)。

struct Node {
    Vehicle[10] a_v; // 10 is max number of Vehicles in array
};
Node myNode;
myNode.a_v[cont] = v;

请记住,如果您想保留这个Node并在其中放置更多的东西,则需要在正确的作用域中声明它。例如,要让您的process函数将Vehicle添加到存在于函数process之外的Node中,您可以这样做:

void Table::process(Node n, Vehicle v, int cont) {
    char a = 'A'+cont;
    putVehicle(a,v);
    if (cont < 10) {
        n.a_v[cont] = v;
    }
    if (cont == 0) a_surt = v.rowVehicle();
}

看起来你只是想使用一个数组。在这种情况下,你要找的是这样的内容:

// This would go somewhere in your program. Again, 10 is just an example.
Vehicle vehicleArray[10];
// Send this array to this function
void Table::process(Vehicle[] vArray, Vehicle v, int cont) {
    char a = 'A'+cont;
    putVehicle(a,v);
    if (cont < 10) { // In a real program, don't hard-code array limits.
        vArray[cont] = v;
    }
    if (cont == 0) a_surt = v.rowVehicle();
}

您应该使用Node对象来访问a_v变量。这条线

Node.a_v[cont]=v;

是不正确的。你应该这样做:

Node n;
n.a_v[cont]=v;

每次我输入这个:Node。它给了我那个错误。

Node是一个类型;类型定义了对象的结构,但是它们没有自己的字段(除了static字段,它一次属于所有实例;它们的访问方式不同)。

为了使用.->操作符,您需要Node实例,如下所示:

Node x;
x.a_v = ...

这是不清楚在您的情况下,从哪里Node实例应该来,虽然。为了访问它们,您需要将它们作为参数传递,或者使它们静态/全局可用(不推荐)。

好的,所以Node不是数组的名称。它是用户定义的类型的名称,应该包含一个数组。但是,您的Node不包含数组。它包含一个名为a_v的Vehicle。我假设a_v代表一个车辆数组。因此,需要分配数组。像这样:

struct Node {
   Vehicle a_v[AMOUNT];
};

如果在编译时不知道数组的大小,则必须动态分配数组,如下所示:

struct Node {
   Vehicle* a_v;
   Node() {
      a_v = new Vehicle[AMOUNT];
   }
};

如果它是动态分配的,那么它也必须被释放:

struct Node {
   Vehicle* a_v;
   Node() {
      a_v = new Vehicle[AMOUNT];
   }
   ~Node() {
      delete[] a_v;
   }
};

并且如果它是动态分配的,则需要添加复制或禁用复制的规定:

struct Node {
   Vehicle* a_v;
   Node() {
      a_v = new Vehicle[AMOUNT];
   }
   ~Node() {
      delete[] a_v;
   }
   // Disable copies (with C++11 support):
   Node(const Node&) = delete;
   Node& operator=(const Node&) = delete;
   // Disable copies (without C++11 support) by making them private and not defining them.
   private:
   Node(const Node&);
   Node& operator=(const Node&);
};

然后访问其中一个车辆,你需要这样做:

Node n;  // Declare a node, which contains an array of Vehicles
n.a_v[cont] = v;  // Copy a Vehicle into the array of Vehicles
但是,请注意,如果在此函数中声明Node实例,则它是局部的,并且一旦函数结束,它就会超出作用域。如果您希望Node实例在函数调用之后持续存在,则需要将其声明为Table的成员。
class Table
{
   private:
      Node n;
};

最后,正如其他人建议的那样,我强烈建议你阅读一本c++书籍来学习c++。我个人推荐这本书(第5版,不要买第6版或第7版——那些版本的作者很糟糕)。