简体   繁体   中英

How can I switch an element from a vector to another in C++?

Yesterday I started learning C++, so I'm pretty new at this. (I come from C#) I'm trying to do a pool with two vectors (active and inactive), so when I need an element I take it from the inactive vector and put it in the active one.

I think I have to delete the pointer from the inactive but keep the element in memory, right? How can I do this?

Here is what In have so far:

    SpritePool::SpritePool(const char *p)
{
    path = p;

}

CCSprite SpritePool::GetSprite(){
    while(poolVectorInactive.size == 0){
        AddSprite();
    }

}

CCSprite SpritePool::AddSprite(){
    CCSprite *s = CCSprite::create(path);
    poolVectorInactive.push_back(*s);
    return *s;

}

Try something like this:

#include <algorithm>
#include <vector>

std::vector<CCSprite*>::iterator it = std::find_if(inactive.begin(), inactive.end(), [](CCSprite* sprite) { /* put your vector search logic (returning bool) here */ });
if (it != inactive.end())
{
    active.push_back(*it);
    inactive.erase(it);
    delete *it;
}

Note that it uses lambda-expressions (see eg http://www.cprogramming.com/c++11/c++11-lambda-closures.html ), so you'll need a C++11 compatible compiler. If you can't afford that luxury, write a function like:

bool matcher(CCSprite* sprite)
{
     /* code here */
}

and change this part:

std::vector<CCSprite*>::iterator it = std::find_if(inactive.begin(), inactive.end(), matcher);

Also, if you can, try to NOT use raw pointers. Store them in eg unique_ptr or shared_ptr , so you don't have to handle deleting them manually. This will save you some leaks and headaches.

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