Let's say I have this:
string opciones[] =
{
"Registrar estudiante",
"Consultar estudiante",
"Eliminar estudiante",
"Atras"
};
and I have a function like this:
construir(string titulo, string opciones[],int n)
and then leave it like this:
construir("Elija una opcion:", string opciones[],4)
I can directly fill the title, and the variable n, but I put the array parameter like this:
construir("Elija una opcion:",{"Registrar","Consultar","Eliminar","Atras"},4)
And the compiler throws me this:
warning: extended initializer lists only available with std c++11 or std gnu++11
error: cannot convert '<brace-enclosed initializer list>' to 'std::__cxx11::string* {aka std::__cxx11::basic_string<char>*}' for argument '2' to 'int construir(std::__cxx11::string, std::__cxx11::string*, int)'|
I would like to know if the data can be declared directly in the parameters of the function as I did with the other two.
Let's analyze the error you got:
The first sentence of the error tells you (my translation) that extended initialization lists are only available as of the C++11 standard.
If you've gotten this error, it's possible that your compiler is capable of the C++11 standard but the option isn't enabled. Try passing
std=c++11
as a compile option and it will let you use the...Extended initialization lists.
They are a new C++ feature introduced in the C++11 standard, they allow (almost) anything enclosed in braces (
{
and}
) to be considered a list. Specifically, a series of data of the same type, separated by commas, enclosed in braces will be translated as the templatestd::initializer_list
.This template contains an arbitrary number of values of the same type, but it is not an array . If you wanted to use it in your function
construir
, you would do it like this:Thus, with C++11 or higher, the following call would be correct:
It would not be necessary to pass the size of the list (you passed a 4) because the compiler counts the elements and you can query them using the member function
std::initializer_list::size
.Extended initialization lists to build collections.
As Dementor 1 has already discussed , it is possible to pass your function
construir
a container and it will accept an initialization list. This is because these types of objects (containers) have a constructor that accepts initialization lists.If you don't have a C++11 or higher compiler...
... forget about passing an initialization list. But you have the option to use templates:
The function would be used [like this] :
There is no need to pass the size parameter because the template detects it.
1 What a bad name royo... :'(
You can use vectors if you pass it as a reference:
And then you can use:
Also note that to use this you need C++11 .