Search code examples
c++visual-studio-codevectorinitialization

Unable to initialize vector with initializer list in visual studio code


#include <vector>
#include <iostream>
using namespace std;

int main()
{
    vector<int> v = {1,2,3,4};
    for (int x : v)
    {
        cout << x << ' ';
    }
return 0;
}

When I run the above code in vscode I receive the following ERROR:

non-aggregate type 'vector' cannot be initialized with an initializer list gcc [7, 17]

NOTICE - the error includes gcc even though that is not the compiler I am using.

The code compiles fine in the terminal and in Xcode so I know it has something to do with vscode. How do I fix this issue?

NOTE - I am using I C/C++ IntelliSense with the following configurations: Compiler Path (/usr/bin/clang++) IntelliSense mode (macros-clang-arm64) Include path (${workspaceFolder}/**) C standard (c17) C++ standard (C++17).


Solution

  • I copied your code and named it test.cpp. I faced the same issue and I solved it by adding some configurations. Find tasks.json and add something in args.

    "args": [
        "-g",
        "-Wall",
        "-std=c++11",
        "test.cpp"
    ]
    

    It works on my MAC! I used command+shift+B to compile and it generated a.out after compiling. Then you can run it by F5. I also post my launch.json here, where /Users/work/Foo is my workspaceFolder. Pay attention to the line of program, I have changed this line. Good luck!

    {
      "version": "0.2.0",
      "configurations": [
        {
          "name": "C/C++ Runner: Debug Session",
          "type": "cppdbg",
          "request": "launch",
          "args": [],
          "stopAtEntry": false,
          "cwd": "/Users/work/Foo",
          "environment": [],
          "program": "/Users/work/Foo/a.out",
          "MIMode": "lldb",
          "externalConsole": true
        }
      ]
    }