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.
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
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?)
- Go to Toolbar -> Settings -> Compiler
- In the "Selected compiler" drop-down menu, make sure "GNU GCC Compiler" is selected
- Below that, select the "compiler settings" tab and then the "compiler flags" tab underneath
- In the list below, make sure the box for "Have g++ follow the C++11 ISO C++ language standard [-std=c++11]" is checked
- Click OK to save
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With