Reputation: 65
I am writing C++ code in vs code on my Macbook. While using the C++ standard template library, i am writing the code
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> array={1,3,4};
for(int x:array)
cout<<x<<" ";
return 0;
}
This code, on compilation gives the error that:
non-aggregate type vector<int> cannot be initialised with an initialiser list.
But when I re-write the code as below, it works totally fine.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> array;
int val;
int n;
cout<<"Give me n:";
cin>>n;
for(int i=0;i<n;++i)
{
cin>>val;
array.push_back(val);
}
return 0;
}
In addition, I tried doing this in JetBrains Clion IDE, and I see that both versions of my code are working fine. Why this problem is happening?
Upvotes: 3
Views: 2482
Reputation: 1
I encountered this issue while working in VS Code, but not in CLion. The problem occurs because Code Runner's default C++ execution command uses g++ without specifying the standard version, which defaults to an older version (C++98 or C++03).
To fix this, open the Code Runner extension settings in settings.json and modify the "cpp" execution command. Change this line:
"cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt"
to "cpp": "cd $dir && g++ -std=c++17 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt"
This ensures that Code Runner compiles your C++ files using C++17, avoiding compatibility issues with modern code. If you need an even newer standard, you can replace -std=c++17 with -std=c++20 .
Upvotes: 0
Reputation: 11
It worked on my environment (VS Code on Mac) by adding "-std=c++11"
into the "args"
list in "tasks.json"
under ".vscode"
folder.
Upvotes: 1
Reputation: 7112
But when i write this same code as:
The other version is not really the same code.
Your problem is with std::vector
initializer list, probably arising from wrong compilation flags passed to your compiler. If you're using mac, try to download and install clang
, then compile and run it. If it dosen't work then re-post.
Upvotes: 3