C++ How to use a map -
im quite noob @ c++ hope question isn't obvious.
i'm creating voxel engine. need chunk on specified xyz location.
the chunk management class has vector<chunk*> loadedchunks.
i can't utilize index location of vector because 1 time move character alter positions because old chunks removed , new chunks added.
in java would've used hashmap<point3d, chunk> i've googled see if c++ has found there class called map.
so tried utilize map , used class called point3d contains x,y,z locations of chunk gave me error because i'm using chunk* point3d wasn't pointer. can't save point3d pointer because still can't location xyz.
now question is, there way utilize map or there maybe improve way chunk @ x,y,z or have stick slowest loop loops through chunks , returns chunk has equal x,y,z?
here code i'm using:
chunkmanager.h ... map<point3d, chunk*> loadedchunks; .... chunkmanager.cpp void chunkmanager::addchunk(chunk* chunk){ loadedchunks.insert(make_pair(point3d(chunk->x, chunk->y, chunk->z), chunk)); chunk* c = loadedchunks[point3d(chunk->x, chunk->y, chunk->z)]; } chunk* chunkmanager::getchunkat(int x, int y, int z){ homecoming loadedchunks[point3d(chunk->x, chunk->y, chunk->z)]; } void chunkmanager::render(renderer& renderer){ for(auto iterator = loadedchunks.begin(); iterator != loadedchunks.end(); iterator++){ iterator->second->render(renderer); } } void chunkmanager::update(double delta){ for(auto iterator = loadedchunks.begin(); iterator != loadedchunks.end(); iterator++){ iterator->second->update(delta); } } point3d: class point3d { public: point3d(int x, int y, int z); int x, y, z; bool operator< (const point3d &rhs) const; }; bool point3d::operator< (const point3d &rhs) const { homecoming x < rhs.x || ( x == rhs.x && ( y < rhs.y || ( y == rhs.y && z < rhs.z))); } i've added operator< , working.
return x < rhs.x || ( x == rhs.x && ( y < rhs.y || ( y == rhs.y && z < rhs.z)));
you can utilize map want. nil pointers.... have other (possibly conceptual) problems there.
but create std::map<point3d, chunk*> loadedchunks;
add values loadedchunks.insert(std::make_pair(my_point3d, my_chunk_ptr));
read them using find() or operator[] - have different behaviour (op[] homecoming reference something, adding new entry if didn't exist, find homecoming pair, bool entry existed or not , iterator entry).
your point3d class need have operator< @ to the lowest degree map can utilize determine in map set point3d.
if think not perform (a map implemented tree structure) can utilize boost, have unordered_map class uses hash table instead.
one thing potentially recommend utilize unique_ptr<> or shared_ptr<> chunk pointers though. these help prevent leaks if don't manage pointer properly.
c++
No comments:
Post a Comment