Filling array with structs

C++

  • (12 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »

170 Replies - 18728 Views - Last Post: 11 January 2011 - 08:01 AM Rate Topic: ***** 2 Votes

#1 Calico  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 105
  • Joined: 08-November 10

Filling array with structs

Posted 08 November 2010 - 07:17 AM

Hi

I am fairly new to C++ and am having trouble with usign structs in 2D arrays. I am modelling a physical storage rack (3 rows high, 14 colums long) as an array. So I have declared my array in the following way:

// Declare a 3x14 array  
const int nNumRows = 3;  
const int nNumCols = 14;  
int nStorageRack[nNumRows][nNumCols]= { 0 };[/color]



I need each element to hold a roll of steel, which will be represented by a struct in the following form:

struct SteelData
{
char chGrade; //type of steel
float fWidth; // width of roll
float fLength; //length when unrolled
bool bEmpty; //is the element occupied? 1=yes 0=no
};


I will have 6 grades of steel, with 2 different lengths of each. So that gives me a total of 12 different sets of struct data. Is it possible to fill the array with structs, but without any data other than the bool variable being false? So like it will have the chGrade variable there... which i can then edit the members individually with a command like:

nStorageRack[Row][Col].fWidth = 1.85; 


I found an example that did the multiplication of elements in a 2D array, and adapted it for my array size:

// Calculate a multiplication table
    for (int nRow = 0; nRow < nNumRows; nRow++)
    {
        for (int nCol = 0; nCol < nNumCols; nCol++)
        {
            nStorageRack[nRow][nCol] = nRow * nCol;
            //if(nCol != 0 && nRow != 0)
                cout << nStoragerack[nRow][nCol] << "\t";
        }
        //if(nRow != 0)
        cout << endl;
    }

Im guessing i will be doing something similar with nested for loops to fill it with structs. but can someone give me a few pointers how to go about doing this.

Any help is appreaciated
Many Thanks :)

MOD EDIT: When posting code...USE CODE TAGS!!!

:code:

This post has been edited by JackOfAllTrades: 08 November 2010 - 09:41 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Filling array with structs

#2 Guest_c.user*


Reputation:

Re: Filling array with structs

Posted 08 November 2010 - 07:41 AM

SteelData nStorageRack[nNumRows][nNumCols] = { { 0 } };
declare the structure type before the array definition

This post has been edited by c.user: 08 November 2010 - 07:42 AM

Was This Post Helpful? 1

#3 newclearner  Icon User is offline

  • D.I.C Regular

Reputation: 103
  • View blog
  • Posts: 302
  • Joined: 29-September 10

Re: Filling array with structs

Posted 08 November 2010 - 08:32 AM

Using code tags would make your code readable and yours/other's life easier.
Was This Post Helpful? 1
  • +
  • -

#4 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5936
  • View blog
  • Posts: 12,862
  • Joined: 16-October 07

Re: Filling array with structs

Posted 08 November 2010 - 08:50 AM

Something like:
struct SteelData {
	char chGrade; //type of steel
	float fWidth; // width of roll
	float fLength; //length when unrolled
	bool bEmpty; //is the element occupied? 1=yes 0=no
	SteelData() : bEmpty(true) { } // initalize to empty
};

const int StorageRackNumRows = 3;  
const int StorageRackNumCols = 14;  
typedef SteelData StorageRack[StorageRackNumRows][StorageRackNumCols];

// ... 
StorageRack rack;



Though just raw arrays are a pain. Two D arrays are worse.

I'd do something like:
struct SteelData {
	int row, col;
	char grade;
	float width, length;
	bool empty;
};

class StorageRack {
private:
	SteelData *data;
public:
	const int Rows, Cols, Size;
	StorageRack(int rows, int cols) : Rows(rows), Cols(cols), Size(rows*cols) {
		data = new SteelData[Size];
		for(int row=0; row<Rows; row++) {
			for(int col=0; col<Cols; col++) {
				SteelData &item = at(row, col);
				item.row = row;
				item.col = col;
				item.empty = true;
			}
		}
	}
	~StorageRack() { delete [] data; }
	SteelData &at(int row, int col) { return data[row*Cols+col]; }
};


Was This Post Helpful? 2
  • +
  • -

#5 Calico  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 105
  • Joined: 08-November 10

Re: Filling array with structs

Posted 08 November 2010 - 10:51 AM

Thank you all for the replies. I apologise for not using the code tags.. thanks for editing them in for me JackOfAllTrades! :)

@baavgai
Thanks for your code, im not sure how public/private classes work to be honest. Is it something that can be avoided? Also im struggling to understand what exactly lines 17-25 (in your second example) are doing. Could you possibly clarify them a bit for me :blush:

Heres what i have so far, havent tried compling it yet.

#include <iostream>
using namespace std;

struct SteelData 
{
    char chGrade; //type of steel
    float fWidth; // width of roll
    float fLength; //length when unrolled
    bool bEmpty; //is the element occupied? 1=yes 0=no
    SteelData() : bEmpty(true) { } // initalize to empty
};
	 
void main()
{
const int StorageRackNumRows = 3; 
const int StorageRackNumCols = 14; 
typedef SteelData StorageRack[StorageRackNumRows][StorageRackNumCols];
	
    for(int row=0; row<StorageRackNumRows; row++) 
    {
        for(int col=0; col<StorageRackNumCols; col++) 
        {
            SteelData &item = at(row, col);
            item.row = row;
            item.col = col;
            item.bEmpty = true;
        }
    }
}


This post has been edited by Calico: 08 November 2010 - 10:53 AM

Was This Post Helpful? 0
  • +
  • -

#6 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5936
  • View blog
  • Posts: 12,862
  • Joined: 16-October 07

Re: Filling array with structs

Posted 08 November 2010 - 11:12 AM

We'll keep it simple then and stick to a 2D array of structs.

This will compile. See if it makes sense:
#include <iostream>
using namespace std;

struct SteelData {
	char chGrade; //type of steel
	float fWidth; // width of roll
	float fLength; //length when unrolled
	bool bEmpty; //is the element occupied? 1=yes 0=no
};

const int StorageRackNumRows = 3;
const int StorageRackNumCols = 14;
// here we define a type alias
typedef SteelData StorageRack[StorageRackNumRows][StorageRackNumCols];
// simply, 
// StorageRack foo;
// becomes the same as declaring
// SteelData foo[StorageRackNumRows][StorageRackNumCols];


void clearRack(StorageRack rack) {
	for(int row=0; row<StorageRackNumRows; row++) {
		for(int col=0; col<StorageRackNumCols; col++) {
			rack[row][col].bEmpty = true;
		}
	}
}

void print(StorageRack rack) { /* your code here */ }

// never void in main!
int main() {
	StorageRack rack; // this is your data that will be passed to various functions
	// first, we probably want to initialize our data
	clearRack(rack);
	return 0;
}



You want declare methods that will modify or use your StorageRack type in certain ways. When you get into classes, those methods will become part of the class.

A print will do pretty much the same double loop.

This post has been edited by baavgai: 08 November 2010 - 11:13 AM

Was This Post Helpful? 1
  • +
  • -

#7 Calico  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 105
  • Joined: 08-November 10

Re: Filling array with structs

Posted 08 November 2010 - 01:00 PM

Wow, thanks for that. You've been a great help!

Yeah that makes sense to me. One point tho, in line 21 you wrote:

void clearRack(StorageRack rack) {


What is the "rack" part in reference to? Should this be:

void clearRack(StorageRack) {


Same thing for line 29. Am I missing something obvious? :dontgetit:

With regard to line 29. For my simulation, the warehouse will recieve steel rolls one by one, so i dont need to do the double loop? I would have to populate different rolls of steel to the array 1 by 1. Going to try that out now, by doing for example:

StorageRack[2][3].chGrade = A;
StorageRack[2][3].fWidth = 1.85;
StorageRack[2][3].fLength = 200;
StorageRack[2][3].bEmpty = false;


for the element in row 2, column 3. Will do this for a test 2x3 storage rack. How would i print the results? would i do a "cout" command for just the "Steel Data" struct.. or individually for each member of the struct in a double loop?

Again, Thanks for all your help so far... really appreciate it :clap:

This post has been edited by Calico: 08 November 2010 - 01:01 PM

Was This Post Helpful? 0
  • +
  • -

#8 Calico  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 105
  • Joined: 08-November 10

Re: Filling array with structs

Posted 08 November 2010 - 01:18 PM

This is what im trying at the moment.. getting a complie error though:

void print(StorageRack rack) {
    for(int row=0; row<StorageRackNumRows; row++) {
        for(int col=0; col<StorageRackNumCols; col++) {
        cout"<<StorageRack[row][col].chGrade" "<<StorageRack[row][col].fWidth" "<<StorageRack[row][col].fLength"<< "\t" endl;
        }
    }
}



Line 4

In function 'void print(SteelData (*)[14])':|
|error: expected ';' before string constant|
||=== Build finished: 1 errors, 0 warnings ===|
Was This Post Helpful? 0
  • +
  • -

#9 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5936
  • View blog
  • Posts: 12,862
  • Joined: 16-October 07

Re: Filling array with structs

Posted 08 November 2010 - 01:22 PM

StorageRack is a type, defined by the typedef. rack is what I chose to call my variable. Don't get hung up on typedef, it's just a good way to be lazy. With it you can do:

typedef SteelData StorageRack[StorageRackNumRows][StorageRackNumCols];

void print(StorageRack someVarName);



Without it:
void print(SteelData someVarName[StorageRackNumRows][StorageRackNumCols]);



Your call.
Was This Post Helpful? 1
  • +
  • -

#10 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5936
  • View blog
  • Posts: 12,862
  • Joined: 16-October 07

Re: Filling array with structs

Posted 08 November 2010 - 01:32 PM

Perhaps you wanted:
cout << rack[row][col].chGrade
	<< " " << rack[row][col].fWidth
	<< " "<<rack[row][col].fLength
	<< endl;



I would generally prefer to make a print for the element as well as the array of elements.

Something like:

void print(const SteelData &item) {
	if (item.bEmpty) {
		cout << "empty";
	} else {
		cout << item.chGrade << " " << item.fWidth << " "<<item.fLength;
	}
}


void print(StorageRack storageRack) {
	for(int row=0; row<StorageRackNumRows; row++) {
		for(int col=0; col<StorageRackNumCols; col++) {
			cout << "(" << row << "," << col << "):";
			print(storageRack[row][col]);
			cout << "\t";
		}
		cout << endl;
	}
}


This post has been edited by baavgai: 08 November 2010 - 01:33 PM

Was This Post Helpful? 1
  • +
  • -

#11 Calico  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 105
  • Joined: 08-November 10

Re: Filling array with structs

Posted 08 November 2010 - 01:40 PM

Thanks! Just ran the code, but nothing shows up, just the return value! :sad3:

#include <iostream>
using namespace std;

struct SteelData{
    char chGrade; //type of steel
    float fWidth; // width of roll
    float fLength; //length when unrolled
    bool bEmpty; //is the element occupied? 1=yes 0=no
};

const int StorageRackNumRows = 3;
const int StorageRackNumCols = 14;
// here we define a type alias
typedef SteelData StorageRack[StorageRackNumRows][StorageRackNumCols];
// simply,
// StorageRack foo;
// becomes the same as declaring
// SteelData foo[StorageRackNumRows][StorageRackNumCols];


void clearRack(StorageRack rack) {
    for(int row=0; row<StorageRackNumRows; row++) {
        for(int col=0; col<StorageRackNumCols; col++) {
            rack[row][col].bEmpty = true;
        }
    }
}

void print(const SteelData &item) {
    if (item.bEmpty) {
        cout << "empty";
    } else {
        cout << item.chGrade << " " << item.fWidth << " "<<item.fLength;
    }
}


void print(StorageRack storageRack) {
    for(int row=0; row<StorageRackNumRows; row++) {
        for(int col=0; col<StorageRackNumCols; col++) {
            cout << "(" << row << "," << col << "):";
            print(storageRack[row][col]);
            cout << "\t";
        }
        cout << endl;
    }
}

int main() {
    StorageRack rack; // this is your data that will be passed to various functions
    // first, we probably want to initialize our data
    clearRack(rack);
    print(StorageRack);
    return 0;
}



I havent added the struct data in yet, would i put that in the int main function? Nevertheless, accroding to your code, i should get a table of displaying "empty" in each cell right?

This post has been edited by Calico: 08 November 2010 - 01:49 PM

Was This Post Helpful? 0
  • +
  • -

#12 janotte  Icon User is offline

  • code > sword
  • member icon

Reputation: 990
  • View blog
  • Posts: 5,141
  • Joined: 28-September 06

Re: Filling array with structs

Posted 08 November 2010 - 01:44 PM

Where are you calling a function that would output anything to the screen?

EDIT
Ah ha
You have changed the posted code.

Which version did you actually test?
The one with the call to the print function or the one without that call?

This post has been edited by janotte: 08 November 2010 - 01:46 PM

Was This Post Helpful? 0
  • +
  • -

#13 Calico  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 105
  • Joined: 08-November 10

Re: Filling array with structs

Posted 08 November 2010 - 01:46 PM

View Postjanotte, on 08 November 2010 - 12:44 PM, said:

Where are you calling a function that would output anything to the screen?


Sorry, i copied accross the wrong version of the code. Ive edited it in.. its line 52 in the int main.

But i know thats not right, do i need to call both print functions?

EDIT: hehe yeah, a sneaky edit :P
i cant compile that updated version! i get the following error at line 53

|error: expected primary-expression before ')' token|

This post has been edited by Calico: 08 November 2010 - 01:48 PM

Was This Post Helpful? 0
  • +
  • -

#14 janotte  Icon User is offline

  • code > sword
  • member icon

Reputation: 990
  • View blog
  • Posts: 5,141
  • Joined: 28-September 06

Re: Filling array with structs

Posted 08 November 2010 - 01:50 PM

Look carefully at your typing.
"StorageRack" is a datatype
"storageRack" is a variable.

Which do you want to print?
HINT - The variable.
Was This Post Helpful? 1
  • +
  • -

#15 Calico  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 105
  • Joined: 08-November 10

Re: Filling array with structs

Posted 08 November 2010 - 01:56 PM

:blush: hehe yeah, i want to print the variables!

But now i get the error on the same line:
error: 'storageRack' was not declared in this scope|

Besides, isnt this going to bypass lines 29-35? and just print out each element row and column?

Surely i need to call both of them together somehow :blink:
Was This Post Helpful? 0
  • +
  • -

  • (12 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »