Jump to content
  • Advertisement


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


Help with a vector of objects

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

If you intended to correct an error in the post then please contact us.

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 this post

Link to post
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
// For STL container compliance

MyObject(const MyObject& o){}
void operator=(const MyObject& o){}

std::vector<MyObject> vec;

void AddNewObject()
MyObject obj;
vec.push_back(obj); // equivalent to vec.insert(vec.end(),obj);


Share this post

Link to post
Share on other sites
The header file.

Class myObject



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


The cpp file


myObject obj3;



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]

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!