Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector c++ 98 error

Tags:

c++

vector

so ive been reading multiple (and resent) c++ books and learning about vectors and they all are telling me to define a vector like this:

 vector<int> v1 = {4 ,3 ,5}; 

however when i compile it (Im using gnu gcc compiler in codeblocks) it comes up with this error

in c++ 98 'v1' must be initialized by constructor not by '{...}' and i also get another one underneath that that sais: could not convert '{4, 3, 5}' from 'brace enclosed initializer list' to 'std::vector v1'

if you could help me it'd be much appreciated. And i did include the vector library.

like image 564
Harry the hacker Avatar asked Mar 23 '16 08:03

Harry the hacker


3 Answers

Follow these steps if you are using Codeblocks:

1.Go to Toolbar -> Settings -> Compiler

2.In the "Selected compiler" drop-down menu, make sure "GNU GCC Compiler" is selected.

3.Below that, select the "compiler settings" tab and then the "compiler flags" tab underneath.

4.In the list below, make sure the box for "Have g++ follow the C++11 ISO C++ language standard [-std=c++11]" is checked.

5.Click OK to save

like image 179
rahul agarwal Avatar answered Sep 22 '22 19:09

rahul agarwal


Initialization used by you is called initializer list and it is supported c++11 onwards.

To ensure code is compiled, use C++11 or later -std option. Or in general, don't use C++98.

If you are using g++, please read: Compiling C++11 with g++


From comments OP is using codeblocks. You can use the following steps before hitting the compile button: (Source: How can I add C++11 support to Code::Blocks compiler?)

  1. Go to Toolbar -> Settings -> Compiler
  2. In the "Selected compiler" drop-down menu, make sure "GNU GCC Compiler" is selected
  3. Below that, select the "compiler settings" tab and then the "compiler flags" tab underneath
  4. In the list below, make sure the box for "Have g++ follow the C++11 ISO C++ language standard [-std=c++11]" is checked
  5. Click OK to save
like image 21
Mohit Jain Avatar answered Nov 09 '22 00:11

Mohit Jain


The C++98 Standard does not support initializer lists to initialize standard containers.

Try to set appropriate compiler options to compile the code according to the C++ 2011 Standard.

Another approach is to add elements to the vector individually like

std::vector<int> v1;
v1.reserve( 3 );

v1.push_back( 4 );
v1.push_back( 3 );
v1.push_back( 5 );

Instead of the member function push_back you can use overloaded operator +=. For example

std::vector<int> v1;
v1.reserve( 3 );

v1 += 4;
v1 += 3;
v1 += 5;

Or to use an array like

const size_t N = 3;
int a[N] = { 4, 3, 5 };
std::vector<int> v1( a, a + N );
like image 6
Vlad from Moscow Avatar answered Nov 09 '22 00:11

Vlad from Moscow