Thor
Thor

Reputation: 10048

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

I'm new to C++ and is trying to learn the concept of vector. However, when I run the code below:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main(){

    vector<string> vs1 = {"a", "an", "the"};

    return 0;
}

The IDE output error message:

error: non-aggregate type 'vector<string>' cannot be initialized with an initializer list
    vector<string> vs1 = {"a", "an", "the"};
                   ^     ~~~~~~~~~~~~~~~~~~

I thought the new C++ standard allow initialisation of a vector from a list of zero or more initial element values enclosed in curly braces. So why the error message?

P.s -- Using auto (which is also introduced in c++11) is fine on my NetBean IDE

Upvotes: 3

Views: 8035

Answers (1)

Jonathan Wakely
Jonathan Wakely

Reputation: 171293

That error comes from the clang compiler, but only if you compile as C++98 / C++03, so that means you are not compiling as C++11.

P.s -- Using auto (which is also introduced in c++11) is fine on my NetBean IDE

(Your IDE doesn't matter, it isn't what compiles the code, a compiler does).

Clang allows auto in C++98 mode, but gives a warning:

prog.cc:8:5: warning: 'auto' type specifier is a C++11 extension [-Wc++11-extensions]

So you need to

  1. Enable C++11 mode

  2. Stop ignoring warnings

Upvotes: 7

Related Questions