1

简单的问题,我只想将地图初始化为空,而不是 nullptr。

 const std::map<std::string, std::string>* emptyDictionary;

我试过

const std::map<std::string, std::string>* emptyDictionary = {"", ""};

但显然这是不对的。多谢你们。

4

3 回答 3

5

你根本忘了做任何地图——你只是做了一个指针!您可以使指针指向动态分配的映射:

 const std::map<std::string, std::string>* emptyDictionary
     = new std::map<std::string, std::string>;

这张地图将是真正的空白。如果您添加初始化程序{{"", ""}},您可能会这样做,那么您实际上并没有一个空映射,而是一个具有一个元素的映射,它将一个空字符串映射到一个空字符串。

请注意,您永远不能通过 const 指针修改您的地图,所以您为什么要这样做有点可疑。

另请注意,肆意的动态分配通常是一种糟糕的编程风格。几乎肯定有更好的方法来做任何你需要做的事情,或者,根据你的评论,你只是严重误解了一些东西:获取指针的最佳方法是获取现有对象的地址:

std::map<std::string, std::string> m;
foo(&m); // pass address of m as a pointer
于 2012-07-05T21:14:06.923 回答
3
const std::map<std::string, std::string>* emptyDictionary 
     = new std::map<std::string, std::string>();
于 2012-07-05T21:14:38.700 回答
1

map 的默认(空)构造函数将创建一个空地图http://www.cplusplus.com/reference/stl/map/map/。只需编写即可在堆栈上声明具有自动分配的映射

std::map<std::string, std::string> emptyDictionary();

并使用 addres-off 运算符将其发送到您的函数

yourfunction(&emptyDictionary);

但是,如果字典比创建它的实例的寿命更长,则需要动态分配它以避免调用其析构函数。

const std::map<std::string, std::string>* emptyDictionary = new std::map<std::string, std::string>();

然后你在调用你的函数时不需要地址运算符。

yourfunction(emptyDictionary);

但是,解除分配的责任将由您承担。当您不再需要该对象时,您需要使用 delete 语句删除该对象。

delete emptyDictionary;
于 2012-07-05T21:22:24.527 回答