Unordered_map - {{key,value},{key,value}}语法无效

unordered_map - {{key,value},{key,value}} syntax invalid

本文关键字:value key 语法 无效 map Unordered      更新时间:2023-10-16

我正在尝试编译从这里获取的代码

// constructing unordered_maps
#include <iostream>
#include <string>
#include <unordered_map>
typedef std::unordered_map<std::string,std::string> stringmap;
stringmap merge (stringmap a,stringmap b) {
  stringmap temp(a); temp.insert(b.begin(),b.end()); return temp;
}
int main ()
{
  stringmap first;                              // empty
  stringmap second ( {{"apple","red"},{"lemon","yellow"}} );       // init list
  stringmap third ( {{"orange","orange"},{"strawberry","red"}} );  // init list
  stringmap fourth (second);                    // copy
  stringmap fifth (merge(third,fourth));        // move
  stringmap sixth (fifth.begin(),fifth.end());  // range
  std::cout << "sixth contains:";
  for (auto& x: sixth) std::cout << " " << x.first << ":" << x.second;
  std::cout << std::endl;
  return 0;
}

与MSVC2012,但我收到

错误C2143:语法错误:'{'之前缺少')'

代码行 上的

stringmap second ( {{"apple","red"},{"lemon","yellow"}} );       // init list

我错过了什么吗?

Visual Studio 2012缺少许多现代c++特性,其中包括initialiser lists

您的代码没有任何问题,使用GCC和Clang可以很好地编译。问题出在Visual c++上。

初始化列表是将在Visual Studio 2012 Update 2中提供的特性之一。这意味着您目前无法在Visual Studio 2012中使用此功能。有一系列的社区技术预览(CTP),但他们带来了一些小问题,包括缺乏智能感知支持和非常明确的免责声明,说他们不打算用于生产代码。

所以,简而言之:你的代码是正确的,但它不会在VS2012中编译,直到微软发布Visual Studio 2012 Update 2。目前还不知道什么时候会发布,但是Visual Studio 2012在2012年8月首次发布,最后一次更新(更新1)是在2012年11月发布的。从那以后,关于这个话题几乎没有什么新闻,但从去年年底开始,它就"即将到来"了。

现在,更新2已经发布。然而,它不包括任何承诺的来自更新2 ctp的c++改进。这很有趣,考虑到它们应该是更新2的预览。显然,Visual c++团队"目前正在完成这些特性的发布计划""将很快分享更多细节"。(来自更新2发布公告的评论)

更准确地说,初始化器列表在VS2012 CTP中有特色,但该更新尚未发布,并且不包含对标准库中初始化器列表的支持-现在,它们很接近,但微软还没有完全完成。