Storing dynamic number of objects | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Storing dynamic number of objects

Say I have a player class and I wanted to store an amount of players given by input. Here's what I've done; I'm just wondering if there's anything wrong with it: class Obj { public: int id; Obj (int id): id (id) {}; }; vector <Obj> objects; int main () { int nObj = 0; cin >> nObj; for (int i = 0; i < nObj; ++i) { objects.push_back (Obj (i)); } return 0; } It just seems too easy to be okay.

7th Jul 2017, 6:38 PM
Zeke Williams
Zeke Williams - avatar
7 Answers
+ 1
Actually, it is that easy :) The things I would change if I were you are: Don't put vector<Obj> objects; in global scope, id shouldn't be publicly accessable, put it under private: instead, Use a prefix for class data members id = _id or m_id or mID, whatever you like. It's just easier to recognize member variables, lastly id is probably never going to change so you might as well make it const.
7th Jul 2017, 8:13 PM
Dennis
Dennis - avatar
+ 3
I would suggest using vector.reserve(nObj); before pushing back with the loop, as this reserves the memory ahead of time instead of it reallocating everytime it doesnt have enough room, which will slow things down.
7th Jul 2017, 9:39 PM
aklex
aklex - avatar
+ 1
It is that easy because they are complex stuff in the vector class ^^
7th Jul 2017, 8:17 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
@Dennis I know, I was using my phone to type that out, so I had everything public. In my actual code, the vector isn't global, for I know of the dangers by making variables global ;) Thanks for the answers!
7th Jul 2017, 9:23 PM
Zeke Williams
Zeke Williams - avatar
+ 1
Ah yea, I forgot about that one, Aklex, good observation. :)
7th Jul 2017, 9:55 PM
Dennis
Dennis - avatar
+ 1
@aklex ah okay, thanks. Good tip
8th Jul 2017, 1:09 AM
Zeke Williams
Zeke Williams - avatar
0
Oh yea, the phone explains everything. I avoid typing code on a phone just for that reason. ^^
7th Jul 2017, 9:33 PM
Dennis
Dennis - avatar