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

Time:03-06

I have written the following code in which I have initialise the vector with along with declaration of vector. Just like array but it is throwing the following error :-

CODE IS :-

# include <iostream>
# include <vector>

using namespace std;

int main()
{
    vector <int> v  = {1,2,3,4,5};
    vector <int> :: iterator it ;
    it = v.begin();

    cout<< (*it) <<endl;
    return 0;
}

THE OUTPUT I RECEIVED IIN TERMINAL IS:-

apple@Apples-MacBook-Air Iterators % cd "/Users/apple/Desktop/CODE/Iterators/" && g   iteratorsBasics.cpp -o iterat
orsBasics && "/Users/apple/Desktop/CODE/Iterators/"iteratorsBasics
iteratorsBasics.cpp:8:18: error: non-aggregate type 'vector<int>' cannot be initialized with an initializer list
    vector <int> v  = {1,2,3,4,5};
                 ^    ~~~~~~~~~~~
1 error generated.
apple@Apples-MacBook-Air Iterators % 

Being the beginner I don't know how to sort this out please help.

the c version I checked in terminal by sawing some videos over internet is as follows:-

Apple clang version 13.0.0 (clang-1300.0.29.30)
Target: arm64-apple-darwin21.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

CodePudding user response:

You are compiling agains C 98 or C 03 standard versions. Add the flag -std=c 11 (or later: c 14/c 17/c 20) to the compiler invocation and it should compile.

Before C 11 std::initializer_list and the std::initializer_list overload of the std::vector constructor did not exist.

CodePudding user response:

Try compiling your code with the following compiler flag:

-std=c  11

So the command:

g   -std=c  11 your_file.cpp
  • Related