c++ - 嵌套结构和数组 C++

标签 c++ arrays struct

你好,我正在处理 C++ 中的嵌套结构和数组,这里是一些背景信息:

 struct Cells // a collection of data cells lines 

     cells :: [Cell] // the cells: a location and a value 

     nCells :: Integer // number of cells in the array

     capacity :: Integer // maximum size of the array end 



struct Cell 
      location :: int // a location of data cells lines 
      value :: int // the value end Cells

我拥有的无法编译的代码(3 个文件、 header 、ADT 实现、主要文件) 我如何在结构数组中声明嵌套结构错误?

// Defines the  cell.h ADT interface
struct Cell;
struct Cells;


struct Cells {
    Cell cells[];
    int nCells;
   int capacity;
};

struct Cell {
   int location;
   int value;
};

//fill cells with random numbers
void initialize(Cells *rcells);

ADT 实现

using namespace std;

#include <iostream>
#include <cstdlib>
#include "cell.h"

void initialize(Cells *rcells){
    for(int i = 0 ; i < rcells->nCells; i++)
   {
        rcells->cells[i].location = rand() % 100;
        rcells->cells[i].value = rand() % 1000;
    }
}

主要

using namespace std;

#include <iostream>
#include <cstdlib>
#include "cell.h"

int main(){
    Cells *c;
    c->cells[0].location=0;
    c->cells[0].value=0;
    c->cells[1].location=0;
    c->cells[1].value=0;
    c->nCells = 2;
    c->capacity = 2;
    initialize(c);
}

最佳答案

您的原始声明失败,因为在

struct Cells {
    Cell cells[];
    int nCells;
    int capacity;
};

以这种方式定义的“单元格”是一个数组,它应该具有固定大小(除非它是最后一个成员并且您使用的是 C99 标准)。你可能认为它和

一样
Cell* cells 

但在结构定义中不会自动转换为指针类型。

做这些事情的C++方法是

typedef std::vector<Cell> Cells;

你的初始化函数可以是

void initialize(int ncell, Cells& cells) {
    cells.resize(ncell);
    for (Cell& cell : cells)
    {
         cell.location = rand() % 100;
         cell.value = rand() % 1000;
    }
}

你的主程序应该稍微改变一下

int main(){
    Cells c;
    initialize(2, c);

    c[0].location=0;
    c[0].value=0;
    c[1].location=0;
    c[1].value=0;
}

如果你想要细胞计数信息,你可以调用

c.size()

不需要capacity变量,因为cell总数没有上限。

顺便说一句,这不是人们通常所说的嵌套结构。当有人说嵌套结构时,他通常指的是嵌套结构定义。包含其他对象的对象没有什么特别之处。

关于c++ - 嵌套结构和数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24986803/

相关文章:

c++ - 有没有办法告诉 C++11 使用 std::string 而不是 const char*?

python - 获取任意长度的所有可能的 str 分区

php - Drupal 7 使用 If 条件 mysql 数据库选择查询

类中的c++动态结构

c++ - 在一行中调用 TDataSet.Locate

c++ - 写 "::namespace::identifier"和 "namespace::identifier"有什么区别?

arrays - 如何使用 PostgreSQL 更新 JSON 数组

c - 为什么在 32 位系统中包含一个 int64 变量时结构大小是 8 的倍数

c - 如何将结构体指针赋值为null?

C++ 指针 : overload operator++