簡體   English   中英

如何獲取 C++ 中 map 中的值的參考?

[英]How can I get a reference of the values in a map in C++?

如果我的游戲玩家與其他實體發生碰撞,我希望它不要移動。 我認為的一種解決方案是跟蹤游戲中的所有實體,並在嘗試移動時檢查它是否會與其中任何一個發生碰撞。 問題是,當循環向量時,我沒有得到實體的引用,而是新值,所以它們有新的 ID,我不能再檢查 ID 是否檢查。

 // Actor.cpp
Actor::Actor(float x, float y) : x(x), y(y), m_MovementSpeed(1), m_Alive(true) {
    // ...
    EntityTracker::addEntity(*this);
    this->ID = EntityTracker::entityAmount();
}

void Actor::move(float _x, float _y) {
    for (auto& e : EntityTracker::entities()) {
        if (this->ID != e->ID && this->collides(*e)) {
            return;
        }
    }

    this->x = this->x + _x * m_MovementSpeed;
    this->y = this->y + _y * m_MovementSpeed;
    this->m_Sprite.move(_x * m_MovementSpeed, _y * m_MovementSpeed);
}

// EntityTracker.cpp
uint64_t EntityTracker::s_EntityAmount = 0;
std::map<uint64_t, Actor> EntityTracker::s_Entities {};

void EntityTracker::addEntity(const Actor& actor) {
    EntityTracker::s_Entities.insert(std::pair<uint64_t, Actor>(s_EntityAmount, actor));
    s_EntityAmount++;
}

std::vector<Actor*> EntityTracker::entities() {
    std::vector<Actor*> actors;

    for (auto& it : EntityTracker::s_Entities) {
        std::cout << it.second.ID << std::endl;
        std::cout << it.first << std::endl;
        actors.push_back(&it.second);
    }

    return actors;
}

// EntityTracker.h
class EntityTracker {
public:
    static void addEntity(const Actor& actor);
    static bool removeEntity(uint64_t ID);
    static uint64_t entityAmount();
    static std::vector<Actor*> entities();
private:
    static uint64_t s_EntityAmount;
    static std::map<uint64_t, Actor> s_Entities;
};

當我按下一個鍵時,std::cout 會打印:

1571901079888 // actor's internal ID from vector
0 // ID from vector
1571901079888
1
1571901079888
0
...

我該如何解決這個問題?

您可以從EntityTracker::entities()返回std::vector<std::reference_wrapper<Actor>>類型的向量,下面是此類使用的示例:

// Original data
std::vector<std::string> vec;
vec.push_back("one");
vec.push_back("two");

// Now its copied as references to rvec
std::vector< std::reference_wrapper<std::string>> rvec;
for(auto& r: vec)
    rvec.push_back(r);
    
// Now output original data using rvec references.
for(auto s: rvec)
    std::cout << s.get() << std::endl;

然后在Actor::move中,您將可以訪問真實 Actor 的引用而不是其副本。 您也可以考慮使用std::share_ptrActor保持為智能指針。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM