所以我有以下内容std::map
:
std::map<int, float*> map;
Run Code Online (Sandbox Code Playgroud)
使用以下方法访问此地图operator []
:
float *pointer = map[123];
Run Code Online (Sandbox Code Playgroud)
现在,如果地图中不存在键123,则指针的值将是未定义的.那是对的吗?确保它是:
template <class T>
struct PtrWithDefault {
T *p;
PtrWithDefault() :p(0) {} // default
PtrWithDefault(T *ptr) :p(ptr) {}
PtrWithDefault(PtrWithDefault other) :p(other.p) {} // copy
operator T *() { return p; }
};
std::map<int, PtrWithDefault<float> > map;
Run Code Online (Sandbox Code Playgroud)
现在这样做可以确保指针的正确初始化.还有其他方法吗?这是一种丑陋的解决方案.我的最终目标是速度:
std::map<int, float*> map;
float *p;
std::map<int, float*>::iterator it = map.find(123);
if(it != map.end())
p = (*it).second; // just get it
else
map[123] = p = 0;
Run Code Online (Sandbox Code Playgroud)
这会比使用默认指针的解决方案更快吗?有没有更好的方法来做到这一点?
编辑
好吧,这对我来说完全是愚蠢的.正如Brian Bi所说,由于零初始化,指针将自动初始化.从C++ 03开始,值初始化就在那里,而C++ 98(这是Visual Studio 2008中唯一可用的标准)却没有.
无论如何,它很容易验证为:
std::map<int, float*> map;
typedef float *P;
float *p = map[123], *p1 = P();
Run Code Online (Sandbox Code Playgroud)
双方p
并p1
确实为空,没有必要担心的事情.