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?
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.