Error Vector C ++ 98

so I read several (and repeatedly) C ++ books and found out about vectors, and they all tell me that I should define such a vector:

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

however, when I compile it (Im using gnu gcc compiler in code blocks), it encounters this error

in C ++ 98, 'v1' should be initialized with a constructor not '{...}' and I also get another one under this that sais: failed to convert '{4, 3, 5}' from 'list of closed parentheses lists 'in' std :: vector v1 '

If you could help me, that would be very grateful. And I turned on the vector library.

+5
source share
3 answers

The initialization you use is called the initializer list and is supported by C ++ 11 onwards.

To ensure code compilation, use the C++11 or later -std . Or, generally speaking, do not use C++98 .

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


Of the comments, OP uses code blocks. You can use the following steps before pressing the compilation button: (Source: How to add C ++ 11 support for the Code :: Blocks compiler? )

  • Go to the toolbar β†’ Settings β†’ Compiler
  • From the Selected Compiler drop-down menu, make sure GNU GCC Compiler is selected
  • Below, select the "Compiler Options" tab, and then the "compiler flags" tab under
  • In the list below, make sure that the "Have g ++ follow C ++ 11 ISO C ++ [-std = C ++ 11]" standard is checked.
  • Click OK to save
+7
source

The C ++ 98 standard does not support initializer lists for initializing standard containers.

Try setting the appropriate compiler options to compile the code in accordance with the C ++ 2011 standard.

Another approach is to add elements to the vector individually, for example

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

Instead of the push_back member function, you can use the overloaded += operator. for instance

 std::vector<int> v1; v1.reserve( 3 ); v1 += 4; v1 += 3; v1 += 5; 

Or use an array of type

 const size_t N = 3; int a[N] = { 4, 3, 5 }; std::vector<int> v1( a, a + N ); 
+4
source

Compile with the compiler option -std = C ++ 11 at the end of the line in the makefile.

So for example:

 g++ -ggdb -O0 -c ENiX_Chocky.cpp -std=c++11 g++ -ggdb -O0 -c ENiX_NLPTest.cpp -std=c++11 ... 

Then, when you communicate, use the -std = C ++ 11 option again:

 g++ -ggdb -O0 ENiX_Chocky.cpp ENiX_NLPTest.cpp -o CLINLPTest.cpp -std=c++11 

The error will disappear immediately.

+2
source

Source: https://habr.com/ru/post/1245610/


All Articles