【问题标题】:C++ maps and pointersC++ 映射和指针
【发布时间】:2014-12-07 22:06:24
【问题描述】:

我必须每次都重新创建地图,而不仅仅是引用已经创建的地图。

这行得通:

void render(Scene *scene) {

     map<std::string, Node*> _map = scene->getNodes(); // I don't want recreate the map every time. It is slowing down the render function :(
     for(auto outer_iter = _map.begin(); outer_iter!= _map.end(); ++outer_iter) {
         outer_iter->second->draw(*scene->getCamera());
     }
}

但这并没有……

 void render(Scene *scene) {

     //map<std::string, Node*> _map = scene->getNodes();
     for(auto outer_iter = scene->getNodes().begin(); outer_iter!= scene->getNodes().end(); ++outer_iter) {
         outer_iter->second->draw(*scene->getCamera());
     }
}

我不明白为什么会这样。

我怎样才能只引用场景中的地图而不每次都重新创建它?

【问题讨论】:

  • 这显示什么错误?
  • map&lt;std::string, Node*&gt; 这样的设计更需要managed pointer 恕我直言。

标签: c++ pointers opengl hashmap stdmap


【解决方案1】:

通过 const 引用返回地图并更改为 const map&lt;std::string, Node*&gt; &amp;_map:

class Scene{
    map<std::string, Node*> map;
public:
    const map<std::string, Node*>& getNodes() const{
        return map;
    }
}

void render(Scene *scene) {

     const map<std::string, Node*> &_map = scene->getNodes(); 
     for(auto outer_iter = _map.begin(); outer_iter!= _map.end(); ++outer_iter) {
         outer_iter->second->draw(*scene->getCamera());
     }
}

这将避免复制每个render 调用,并且只在地图上操作n

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 2013-10-12
    • 2021-10-07
    • 1970-01-01
    相关资源
    最近更新 更多