Nested Struct and Array C++ -
Hello, I am working with Nested Stracts and Array in C ++, here are some background information:
Code> A collection of cells in the structure room / data cells : [Cell] // cell: a location and a value nCells :: integer // Number of cells in array capacity :: integer // maximum size array end structure cell location :: int // data cell lines have a location value :: int // values end cellswith me Od which will not compile (3 files, header, ADT implementation, I am Main) How do I tell incorrectly nested structure structure array?
// cell defines the AHDT interface structure; Structure cell; Cells [cell cells] []; Int nCells; Int capacity; }; Struct cell {int location; Intestine value; }; // Fill in random number zero initial cells (cell * rcells);
ADT implementation
using namespace std; # Include & lt; Iostream & gt; # Include & lt; Cstdlib & gt; #include "cell.h" zero start (cell * rcells) {for (int i = 0; i
nCells; i ++) {rcells- & gt; Cells [i]. Location = rand ()% 100; Rcells-> Cells [i] .value = rand ()% 1000; }} main
using namespace std; # Include & lt; Iostream & gt; # Include & lt; Cstdlib & gt; #include "cell.h" int main () {cell * C; C & gt; Cells [0] .location = 0; C & gt; Cells [0] .Value = 0; C & gt; Cells [1] .location = 0; C & gt; Cells [1] .Value = 0; C-> CCL = 2; C-> capacity = 2; Start (c);
Your original announcement fails because
Cells [cell cells] []; Int nCells; Int capacity; };
A defined "cells" is defined as an array, whose size should be fixed (unless it is the last member and you are using the C99 standard). You might think that this is similar to
cell * cells
, but it will not be defined in the composition type in its own voice.
The C ++ method of doing such things
typedef std :: vector & lt; Cell & gt; Cells;
Your initialization function may be
zero starting (int ncell, cell and cells) {cells.resize (ncell); For (cell and cell: cells) {cell.location = rand ()% 100; Cell.value = rand ()% 1000; }}
Your main program should be slightly shorter
int main () {cells c; Start (2, c); C [0] .location = 0; C [0] .value = 0; C [1] .location = 0; C [1] .Value = 0; }
If you want cell calculation information, you can call
c.size ()
There is no need for capacity variables because there is no upper limit on the total number of cells.
By the way, nested structures usually do not talk about it. When a nested straight says, then this often means nested structure definition. There is nothing special about the object that contains other objects.
Comments
Post a Comment