int Dia[DIAS_SEMANA];
Here you are declaring an array of fixed size. Although Dia
is managed as if it were a pointer, that is, you can do the following:
int* ptr = Dia;
Fixed-size arrays have certain peculiarities with respect to the pointers of a lifetime:
- Are stored in the program's stack
- Its size can not be changed at run time
- Your memory can not be released with
delete
or free
On the other hand, as you say @ SJuan76 , the C ++ pointers do not have methods ... it happens that in C ++ the arrays of fixed size, do not either.
Well, although you can not ask its size directly, this data is not essential, since you know that the range of values goes from 0 to DIAS_SEMANA
, then the loop could look like this:
for(int i=0; i<DIAS_SEMANA; i++)
Now, since you use a list for the days of the week, it is not too clean to assign a value to the last item manually (which is also the value you use for top . The normal thing is to leave the enumerated one without values:
enum Semana{Lunes, Martes, Miercoles, Jueves, Viernes, Sabado, Domingo, DIAS_SEMANA};
Or, if we want to generalize it even more:
enum Semana{Lunes, Martes, Miercoles, Jueves, Viernes, Sabado, Domingo, INICIO = Lunes, DIAS_SEMANA};
Why?
Well basically because if not the iterations are a bit weird. Any C ++ programmer will find it more natural to have a loop such that:
for( Semana i = INICIO; i < DIAS_SEMANA; i++ )
Dia[i] = /* ... */;
that the alternative that your code raises:
for( Semana i = Lunes; i <= DIAS_SEMANA; i++ )
Dia[i-1] = /* ... */;
// ^ OJO que en tu codigo tienes que Lunes=1
Bonus
The fixed-size arrays have as an additional feature that the compiler knows at all times how many bytes they occupy, which allows you to calculate its size in a " simple ":
int numElementos = sizeof(Dia)/sizeof(Dia[0]);
Although, on the other hand, if we want our fixed-size array to have methods, what we can do is use std::array
(C ++ 11 onwards):
#include <array>
#include <iostream>
using namespace std;
int main(){
enum Semana{ Lunes, Martes, Miercoles, Jueves, Viernes, Sabado, Domingo, DIAS_SEMANA};
std::array<int,DIAS_SEMANA> Dia;
// Iteracion por indices
for(size_t i=0; i<Dia.size(); i++){
cout<<Dia[i]<<endl;
}
// Iteracion por iteradores
for(std::array<int,DIAS_SEMANA>::iterator it = Dia.begin(); it != Dia.end(); ++it){
cout<<*it<<endl;
}
// Iteracion por iteradores (C++11)
for(auto it = Dia.begin(); it != Dia.end(); ++it){
cout<<*it<<endl;
}
// for basado en rangos
for(int item : Dia){
cout<<item<<endl;
}
}
Bonus 2
In C, if we do not put void
in the parameters of a function, what we get is that this function accepts an indeterminate number of parameters ... however in C ++ that void
is implicit, so if we leave the function simply as int main()
we will get the same effect as with int main(void)
but with a cleaner code.