VSCode下C++ unordered_map列表初始化编译错误求助
VSCode中unordered_map初始化列表报错问题
问题描述
尝试用初始化列表初始化unordered_map,代码如下:
const unordered_map <int, int> prova = { {0,1}, {4,2} };
在VSCode内编译时持续报错:error: non-aggregate type 'const unordered_map<int, int>' cannot be initialized with an initializer list
已在c_cpp_properties.json中配置-std=c++20,并尝试多种编译器组合,结果一致。但终端执行g++ -std=c++20 -o prova prova.cpp编译正常,省略-std=c++20则出现相同错误。
系统环境
g++ --version输出:
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/4.2.1 Apple clang version 13.0.0 (clang-1300.0.29.30) Target: x86_64-apple-darwin20.6.0 Thread model: posix InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
VSCode配置
.vscode/settings.json为空.vscode/c_cpp_properties.json:
{ "configurations": [ { "name": "Mac", "includePath": [ "${workspaceFolder}/**" ], "defines": [], "macFrameworkPath": [ "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks" ], "compilerPath": "/usr/bin/g++", "cStandard": "c17", "cppStandard": "c++20", "intelliSenseMode": "macos-clang-x64", "compilerArgs": [ "-std=c++20" ] } ], "version": 4 }
.vscode/tasks.json:
{ "tasks": [ { "type": "cppbuild", "label": "C/C++: clang++ compila il file attivo", "command": "/usr/bin/clang++", "args": [ "-fcolor-diagnostics", "-fansi-escape-codes", "-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "Attività generata dal debugger." } ], "version": "2.0.0" }
问题原因
c_cpp_properties.json中的配置仅用于IntelliSense代码提示,不会作用于实际编译过程。VSCode默认的编译任务(tasks.json)里没有添加-std=c++20参数,导致编译器以旧C++标准编译,而旧标准下无法用初始化列表正确初始化const unordered_map。终端编译时手动指定了-std=c++20,因此能正常通过。
解决方法
修改.vscode/tasks.json,在编译参数args数组中加入-std=c++20:
{ "tasks": [ { "type": "cppbuild", "label": "C/C++: clang++ compila il file attivo", "command": "/usr/bin/clang++", "args": [ "-fcolor-diagnostics", "-fansi-escape-codes", "-g", "-std=c++20", // 添加该行启用C++20标准 "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "Attività generata dal debugger." } ], "version": "2.0.0" }
如果偏好使用g++编译,可将command字段改为/usr/bin/g++,其余参数无需调整。
内容的提问来源于stack exchange,提问作者user13407848
相关产品推荐
相关产品推荐

