Enum to unsigned int

I have the following code:

class mph {
public:
enum minute_periods {five, ten, fifteen, thirty}; 
   std::vector<minute_periods> factors;
  minute_periods fac;

void setUpFactors(void) { 
    factors.resize(4);
    factors[five] = 5;
    factors[ten] = 10;
    factors[fifteen] = 15;
    factors[thirty] = 30;
  }

and I get the following error:

error: invalid conversion from ‘int’ to ‘mph::minute_periods’

how can i fix this?

+3
source share
6 answers

intimplicitly applied to enums, you need to do this explicitly, so you get an error. I don't think this code will do what you want, but it looks like you want something like this.

    std::map<minute_periods, int> factors;

Thus, it factors[five]will provide you with an int, and not enum, like this vector. I assume this is your code because the values ​​5, 10, 15, and 30 are out of range enum(0 to 3).

+3
source

In C ++, you can implicitly drop from enumto int, but not vice versa. You can fix this using explicit casts:

factors.resize(4);
factors[five] = minute_period(5);
factors[ten] = minute_period(10);
factors[fifteen] = minute_period(15);
factors[thirty] = minute_period(30);

, !

+2

enum ints, ints . , . ,

factors[five] = five;
factors[ten] = ten;
factors[fifteen] = fifteen;
factors[thirty] = thirty;

.

+1

:

  • enum vector
  • enum

. vector . , map<minute_period, int>, - .

enum , :

enum minute_periods 
{
    five = 5, 
    ten = 10, 
    fifteen = 15, 
    thirty = 30
}; 

enum - - , .

+1

std::vector<unsigned int> factors;, . , , . .

count . .

0

map a vector. , , , minute_periods

class mph {
public:
enum minute_periods {five, ten, fifteen, thirty}; 
   std::map<minute_periods, int> factors;

void setUpFactors(void) { 
    factors[five] = 5;
    factors[ten] = 10;
    factors[fifteen] = 15;
    factors[thirty] = 30;
  }
};

, :

class mph {
    public:
    enum minute_periods {five = 5, ten = 10, fifteen = 15, thirty = 30}; 
};
0

All Articles