Ian
Ian

Reputation: 787

Error: non-aggregate type 'vector<int>' cannot be initialized with an initializer list

I am a beginner in c++ and every time I run vector<int> nums = {2, 5, 3, 7, 1}; it gives me the Error: non-arregrate type vector cannot be initialized with initializer list.

Can you tell me why?

Thanks,

Upvotes: 66

Views: 86046

Answers (4)

SeanTwomey
SeanTwomey

Reputation: 39

I came across this issue when running C++ code with VS Code's Code Runner extension. To resolve it, I had to use a combination of the above answers by performing the following:

  1. Locate Code Runner in the installed list of extensions
  2. Right-click or select gear icon, and select Extension Settings
  3. The settings.json file will open. Locate the "code-runner.executorMap" block
  4. Change the "cpp": entry to "cd $dir && g++ -std=c++17 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
  5. Save the settings.json file

C++17 above can also be changed to other versions as noted in the other answers.

Upvotes: 2

Abhishek-udaan
Abhishek-udaan

Reputation: 41

If you are using VS code, then go to settings.json, Add "-std=c++17", "-stdlib=libc++" in the args array.

Attached the screenshot of the settings.json for reference

Upvotes: 4

Mote Zart
Mote Zart

Reputation: 960

Using Druhv Sehgal's answer above, this worked for me on mac

If command not found: gcc++ try

clang++ -std=c++11 <filename>

Upvotes: 10

Dhruv Sehgal
Dhruv Sehgal

Reputation: 1582

Use g++ -std=c++11 <filename> when compiling.

Upvotes: 117

Related Questions