简体   繁体   中英

Vector of Pointers. How to use?

I've been currently learning c++ for a project of mine. At the moment, I am thinking about using a vector of pointers to a class (which I will fill with classes derived from this base class) because I want to access unique functions specific to every derived class. I am not entirely sure how to go about using it though, and from my experience with a normal vector, I understand how it can be a pain in the ass to get working, so I just want to know a couple of things:

  1. How can I add an object to the vector?

  2. How do I delete a single element in the vector?

  3. How to I access a specific object through the iterator? For instance, how do I access the functions of an object that has a pointer in the vector?

  4. How do I pass an iterator to a function that takes a pointer to an object as an argument?

Also is there anything else I should know?

Example setup,

class Base
{
};

class DerivedOne : public Base
{
};

class DerivedTwo : public Base
{
};

std::vector<Base*> ptrVec;

To add ,

ptrVec.push_back(new DerivedOne());
ptrVec.push_back(new DerivedTwo());

To delete ,

std::vector<Base*>::iterator it;
/* Make sure it points to the correct element. */
delete *it;
ptrVec.erase(it);

Accessing a function is easy,

Base* ptrToObj = *it; // Assuming it points to the correct element
ptrToObj->AnyFunc(); // You can also use (*it)->AnyFunc()

Answer to your 4th question ,

AnyFuncThatAcceptsObjPtr(*it); // Again assuming it points to the correct element

Also is there anything else I should know?

Yes, learn about smart pointers .

std::vector<SomeSmartPtr<Base> > smartPtrVec;

SomeSmartPtr<Base> smartPtr(new DerivedOne());
smartPtrVec.push_back(smartPtr);

smartPtrVec.erase(it); // With smart pointers, you don't need to delete explicitly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM