是否允许将空值插入C++ std :: map?

MrD*_*Duk 2 c++ stdmap std

我正在考虑一个棋盘设计,并想做一些事情:

typedef std::map <std::string, CheckerPiece> MapType;
MapType CheckerBoard;

CheckerBoard.insert({"a1", null});
Run Code Online (Sandbox Code Playgroud)

这是允许的,还是有办法做类似的事情?我的想法是,我想保持一个板状态,同时将CheckerPiece对象从一个位置移动到另一个位置.

编辑: 沿着相同的路线,是否可以执行以下操作:

CheckerBoard.insert({"a1", new CheckerPiece()});
Run Code Online (Sandbox Code Playgroud)

jua*_*nza 8

你的地图没有CheckerPiece指针,所以你要做的事情甚至都不会编译,除非你有一个隐含的构造函数CheckerPrice,它将指针作为参数.这忽略了这个事实null并不意味着什么C++.假设你的意思是NULL或者nullptr,你不能插入其中任何一个或者结果

new CheckerPiece()
Run Code Online (Sandbox Code Playgroud)

进入你的地图,期间.上面的表达式返回一个指针CheckerPiece.

C++没有类型的空值概念(除非你专门设计一个).解决方法是使用包装类型为您提供可选的语义,即允许您检查某些内容是否已"设置".一个例子是boost :: optional.

这是一个未经测试的例子:

#include <boost/optional.hpp>

boost::optional<CheckerPiece> piece;

if (piece) {
  // piece is not set, we should never get here
}

piece.reset(CheckerPiece( constructor arguments...));

if (piece) {
  // piece is set, use it!
  piece.move();
}
Run Code Online (Sandbox Code Playgroud)