+ 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.
7 ответов
+ 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.
+ 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.
+ 1
It is that easy because they are complex stuff in the vector class ^^
+ 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!
+ 1
Ah yea, I forgot about that one, Aklex, good observation. :)
+ 1
@aklex ah okay, thanks. Good tip
0
Oh yea, the phone explains everything. I avoid typing code on a phone just for that reason. ^^