#### Archived

This topic is now archived and is closed to further replies.

# Help with a vector of objects

This topic is 5680 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I use the vector class in C++ to create a vector of objects like this: vector ObjectVector; I can add objects and access them fine if the objects are declared in my header file. What I would like to do is be able to add Objects to my my Vector likes this. someFunction() { myObject obj; ObjectVector.insert(ObjectVector.end(), obj); } I can do it if myObject is declared in the header file. I think the problem might be a scope one, since the object was created in the function, when the function ends, the obj is destoryed. Is there any way to make this work?

##### Share on other sites
This is an incredibly obtuse question.

I''ll offer an answer, although I don''t even know if it applies, since I don''t really understand what the heck you''re talking about.

  #include <vector>class MyObject{public:  MyObject(){}  // For STL container compliance  MyObject(const MyObject& o){}  void operator=(const MyObject& o){}  ~MyObject(){}};std::vector<MyObject> vec;void AddNewObject(){  MyObject obj;  vec.push_back(obj); // equivalent to vec.insert(vec.end(),obj);}

##### Share on other sites

Class myObject
{

myObject();
~myObject();

doVector();
doAction();

myObject obj1;
myObject obj2;
std::vector myObjectVector;

}

The cpp file

myObject::myObject()
{
myObjectVector.push_back(obj1);
myObjectVector.push_back(obj2);

myObject obj3;

myObjectVector.push_back(obj3);

}

myObject::doStuff()
{
myObjectVector.at(0).doAction();//works
myObjectVector.at(1).doAction();//works
myObjectVector.at(3).doAction();// doesn't work
}

I can access the first two objects in the vector because they have class scope ( I think thats why). The last obj was created in the constructor, and when I try to access it, it doesn nothing. Now, in my code, I use two different class, so one class has a vector of objects of the second class. I wanted to know if there was a way to make the 3 object in my vector.
I don't get any errors, it just doesn't work for objects I added the vector the way I added the thrid one in the example.

[edited by - Hellfire on January 31, 2003 1:40:49 PM]

1. 1
2. 2
JoeJ
20
3. 3
4. 4
frob
12
5. 5

• 13
• 19
• 13
• 20
• 13
• ### Forum Statistics

• Total Topics
632194
• Total Posts
3004692

×