Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

vector

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

like image 828
Thor Avatar asked Jan 29 '26 02:01

Thor


1 Answers

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

like image 199
Jonathan Wakely Avatar answered Jan 30 '26 20:01

Jonathan Wakely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!