Dboy Dhruvil
Dboy Dhruvil

Reputation: 7

Error: non-aggregate type 'vector<int>' cannot be initialized with an initializer list. How to solve?

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

Upvotes: -2

Views: 2335

Answers (4)

Yogesh Joshi
Yogesh Joshi

Reputation: 11

  1. Go to code runner extension settings, then scroll down till you see this executor map. Click on Edit in settings.json. Click on Edit in settings.json
  2. Press cmd+f then search for code-runner.executorMap Make changes at highlighted place only
  3. Then under cpp, write -std=c++17 after g++ as show in the ss.
  4. Save it, and run you program.

Upvotes: 1

Jason
Jason

Reputation: 307

add this

set(CMAKE_CXX_FLAGS "-std=c++11")

into the CMakeList.txt if you use CMake

Upvotes: 0

The Coding Fox
The Coding Fox

Reputation: 1585

Try compiling your code with the following compiler flag:

-std=c++11

So the command:

g++ -std=c++11 your_file.cpp

Upvotes: 1

user17732522
user17732522

Reputation: 76688

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.

Upvotes: 2

Related Questions