Jump to content

C++ Array of Objects

Go to solution Solved by fizzlesticks,

They are not all the same, so would you recommend using struct instead? I would have to write every single (thing[number].otherthing = blabla;) though.

Structs and classes are pretty much the same thing, so that wouldn't change anything.

You could have multiple constructors, one that takes no arguments used to create the array and another that takes all the data and copy new objects into the array like:

class A{public:        A(){}	A(int i, float x) : name(i), num(x){}	int name;	float num;};int main(){	A as[10];	as[0] = A(1, 0.2f);	as[1] = A(4, 0.0f);	as[2] = A(6, 1.3f);	return 0;}

Or use pointers

class A{public:	A(int i, float x) : name(i), num(x){}	int name;	float num;};int main(){	A* as[10];	as[0] = new A(1, 0.2f);	as[1] = new A(4, 0.0f);	as[2] = new A(6, 1.3f);	//...	as[10] = new A(10,1.2f);	cout << as[1]->name;	for(int i=0;i<10;++i)	{		delete as[i];	}	return 0;}

edit: A better way of doing the first method would be like this without the pointless default constructor.

class A{public:	A(int i, float x) : name(i), num(x){}	int name;	float num;};int main(){	A as[10] { A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f)};	return 0;}

 

I want to use an array of objects to be able to call them by typing

for (int = 0; i < 10; i++)    cout << thing[i].name;

and then it would output all of their names. Before they were just called thing1, thing2... so I couldn't really increment them by writing thingi, if you get what I mean.

 

Thanks for the help, I'm really loving c++!

Link to comment
https://linustechtips.com/topic/247275-c-array-of-objects/
Share on other sites

Link to post
Share on other sites

Just searching yields a few good results: 

http://www.java2s.com/Tutorial/Cpp/0180__Class/Createanarrayofobjects.htm

https://www.hscripts.com/tutorials/cpp/array-of-objects.php

 

I haven't worked in c++ for over 2 years so cannot give you exact syntax off the top of my head.

 

Something like:

 

class* classArr = new class[num];

 

Don't forget garbage clean up...

Link to comment
https://linustechtips.com/topic/247275-c-array-of-objects/#findComment-3392251
Share on other sites

Link to post
Share on other sites

^

Or to make it cleaner

class thing <----------- this is your class / object{private :int i;public:thing() <-------- Constructor{ i =0; }SetData (int x) <--------------- set the value of the data{ i=x; }GetData() <----------- give you the value of the object / data{ return i; }}int main (){thing data[10];for (int counter=0;counter<10;counter++){data[counter].SetData(counter); <------------ Modify this part yourself. I made it the value of counter will be the value of your object;}cout << data[0].GetData();}

MB :MSI Z77a G45 | Proc: I5 3570K (Stock) | HSF : CM 212X turbo | RAM : Corsair Vengeance 8GB (2X4GB) | VGA : MSI GTX 660 Twin Frozr | PSU : Corsair GS600 | Case : CM Storm Enforcer | Storage :  OCZ Vector 128GB, WD Blue 500GB , Samsung 840 Evo 120GB, WD Blue 1TB

Link to comment
https://linustechtips.com/topic/247275-c-array-of-objects/#findComment-3392496
Share on other sites

Link to post
Share on other sites

#include <iostream>#include <string>class A {public:int name;};int main() {	A as[10];	for(int i=0;i<10;++i)		as[i].name = i;	for (int i = 0; i<10; ++i)		std::cout << as[i].name << std::endl;	return 0;}

Thanks now that I understand that part, how would I make a constructor for an array of 5 A objects that sets their name.

 

 

^

Or to make it cleaner

class thing <----------- this is your class / object{private :int i;public:thing() <-------- Constructor{ i =0; }SetData (int x) <--------------- set the value of the data{ i=x; }GetData() <----------- give you the value of the object / data{ return i; }}int main (){thing data[10];for (int counter=0;counter<10;counter++){data[counter].SetData(counter); <------------ Modify this part yourself. I made it the value of counter will be the value of your object;}cout << data[0].GetData();}

Could I just make one constructor to set all the data of the array of thing objects? I don't need to display anything.

Link to comment
https://linustechtips.com/topic/247275-c-array-of-objects/#findComment-3392712
Share on other sites

Link to post
Share on other sites

Thanks now that I understand that part, how would I make a constructor for an array of 5 A objects that sets their name.

If the data of every object is the same you can use a vector instead of an array. The first argument for the vector is the number of objects and the second is an object that will be copied to all the objects in the vector.

class A{public:	A(int i) : name(i){}	int name;};int main(){	vector<A> as(10,A(2));	for (int i = 0; i<10; ++i)	{		std::cout << as[i].name << std::endl;	}	return 0;}

If the data is different for each object, there is no nice way of doing it.

1474412270.2748842

Link to comment
https://linustechtips.com/topic/247275-c-array-of-objects/#findComment-3392749
Share on other sites

Link to post
Share on other sites

If the data of every object is the same you can use a vector instead of an array. The first argument for the vector is the number of objects and the second is an object that will be copied to all the objects in the vector.

class A{public:	A(int i) : name(i){}	int name;};int main(){	vector<A> as(10,A(2));	for (int i = 0; i<10; ++i)	{		std::cout << as[i].name << std::endl;	}	return 0;}

If the data is different for each object, there is no nice way of doing it.

They are not all the same, so would you recommend using struct instead? I would have to write every single (thing[number].otherthing = blabla;) though.

Link to comment
https://linustechtips.com/topic/247275-c-array-of-objects/#findComment-3392765
Share on other sites

Link to post
Share on other sites

They are not all the same, so would you recommend using struct instead? I would have to write every single (thing[number].otherthing = blabla;) though.

Structs and classes are pretty much the same thing, so that wouldn't change anything.

You could have multiple constructors, one that takes no arguments used to create the array and another that takes all the data and copy new objects into the array like:

class A{public:        A(){}	A(int i, float x) : name(i), num(x){}	int name;	float num;};int main(){	A as[10];	as[0] = A(1, 0.2f);	as[1] = A(4, 0.0f);	as[2] = A(6, 1.3f);	return 0;}

Or use pointers

class A{public:	A(int i, float x) : name(i), num(x){}	int name;	float num;};int main(){	A* as[10];	as[0] = new A(1, 0.2f);	as[1] = new A(4, 0.0f);	as[2] = new A(6, 1.3f);	//...	as[10] = new A(10,1.2f);	cout << as[1]->name;	for(int i=0;i<10;++i)	{		delete as[i];	}	return 0;}

edit: A better way of doing the first method would be like this without the pointless default constructor.

class A{public:	A(int i, float x) : name(i), num(x){}	int name;	float num;};int main(){	A as[10] { A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f)};	return 0;}

 

1474412270.2748842

Link to comment
https://linustechtips.com/topic/247275-c-array-of-objects/#findComment-3392816
Share on other sites

Link to post
Share on other sites

edit: A better way of doing the first method would be like this without the pointless default constructor.

class A{public:	A(int i, float x) : name(i), num(x){}	int name;	float num;};int main(){	A as[10] { A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f), A(0, .1f)};	return 0;}

Thanks this works great and is manageable for me :)

I did separate them onto different lines because I didn't want a spike in my code.

Link to comment
https://linustechtips.com/topic/247275-c-array-of-objects/#findComment-3392853
Share on other sites

Link to post
Share on other sites

Ok so now I am trying to place these objects (kind of) onto the grid. They're randomly generating coordinates and a direction. It should be checking if there is another boat in the way and that it doesn't go off the grid, but is only doing the ladder. I might need to touch up my knowledge on switches or theres I dumb typo / mistake somewhere in this code that I couldn't find.

#include <iostream>#include <string>#include <ctime>using namespace std;char grid[10][10] = { { ' ' } };class Ships {public:	Ships(string s, int l, char d, bool a) : name(s), length(l), display(d), afloat(a) {}		string name;		int length;		char display;		bool afloat;};void showGrid() {	char r = 'A';	//system("cls");	cout << "   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |" << endl << "___|___|___|___|___|___|___|___|___|___|___|" << endl;	for (int y = 0; y < 10; y++) {		cout << " " << r++ << " ";		for (int x = 0; x < 10; x++)			cout << "| " << grid[x][y] << " "; // if grid[x][y] is a boat character don't show it		cout << "|" << endl << "___|___|___|___|___|___|___|___|___|___|___|" << endl;	}}void placeShips() {	Ships ship[5] { Ships("Aircraft Carrier", 5, 'A', false), 		Ships("Battleship", 4, 'B', false),		Ships("Cruiser", 3, 'C', false),		Ships("Submarine", 3, 'S', false),		Ships("Destroyer", 2, 'D', false)	};	srand(time(NULL));	for (int s = 0; s < 5; s++) {		while (!ship[s].afloat) {			int x = rand() % 10;			int y = rand() % 10;			int d = rand() % 4;			switch (d) { // could seperate them into 2 directions, vertical and horizontal			case 0: // up				if (y - ship[s].length < 0)					break;				else {					for (int q = 0; q < ship[s].length; q++) {						if (grid[x][y - q] != ' ')							break;					}					for (int e = 0; e < ship[s].length; e++) {						grid[x][y - e] = ship[s].display;					}					ship[s].afloat = true;					break;				}			case 1: // right				if (x + ship[s].length > 9)					break;				else {					for (int q = 0; q < ship[s].length; q++) {						if (grid[x + q][y] != ' ')							break;					}					for (int e = 0; e < ship[s].length; e++) {						grid[x + e][y] = ship[s].display;					}					ship[s].afloat = true;					break;				}			case 2: // down				if (y + ship[s].length > 9)					break;				else {					for (int q = 0; q < ship[s].length; q++) {						if (grid[x][y + q] != ' ')							break;					}					for (int e = 0; e < ship[s].length; e++) {						grid[x][y + e] = ship[s].display;					}					ship[s].afloat = true;					break;				}			case 3: // left				if (x - ship[s].length < 0)					break;				else {					for (int q = 0; q < ship[s].length; q++) {						if (grid[x - q][y] != ' ')							break;					}					for (int e = 0; e < ship[s].length; e++) {						grid[x - e][y] = ship[s].display;					}					ship[s].afloat = true;					break;				}			}		}	}}int main() {	placeShips();	showGrid();	return 0;}

It works most of the time, but sometimes it doesn't:

FdKpC5u.pngaII2AbK.pngBhuTTeZ.png

Edit: I will also be splitting the switch into only 2 directions later by creating a random number, 1 or 2 for vertical and horizontal and another of random number, that is either -1 or +1 so I can multiply them. My idea is better in my head :P

Link to comment
https://linustechtips.com/topic/247275-c-array-of-objects/#findComment-3398372
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×