c++ error, vector of classes
Hi, I have a vector of classes, and I need to initialize each one...
so when I declare my vector I do
apvector b(0);
this declares a vector of buildings of size 0.
now, when I want to initialize each one, what do i do?
b.resize(1); //resize the vector
b[0] = building("building name", 5);
this gets an error of "Call of nonfunction"
any ideas?
Two possibilities:
For the latter:
[edited by - Kippesoep on June 4, 2003 10:53:54 AM]
- Use an array of pointers, or...
- Make sure your objects have a copy constructor/assignment operator and copy them into the vector.
For the latter:
class Foo{public : //Constructor Foo (int i) { m_num = i; } //Copy constructor Foo (const Foo &rhs) { *this = rhs; } //Assignment operator void operator = (const Foo &rhs) { m_num = rhs.m_num; }private : int m_num;};...std::vector <Foo> myVector;//Make enough room (not strictly necessary)myVector.reserve (15);//Add 15 objectsfor (int i = 0; i < 15; i++){ //Create new object Foo temp (i); //Add a copy into the vector myVector.push_back (temp);}...
[edited by - Kippesoep on June 4, 2003 10:53:54 AM]
b.push_back(building("building name", 5));
is more compact and efficient than
b.resize(1)
b[0] = building("building name", 5);
is more compact and efficient than
b.resize(1)
b[0] = building("building name", 5);
Read the post more closely, guys. This is an
Now, you say you get a compile error? What''s the exact error, and on what line is it? Try initializing your array to at least a single element.
apvector
, used for the Advanced Placement tests. There is no push_back
.Now, you say you get a compile error? What''s the exact error, and on what line is it? Try initializing your array to at least a single element.
It should still work with pointers or a copy-constructor/assignment operator, even without push_back.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement