Iterating over an enum (or not)
Hi,
I have the following class:
class ReadIntensity {
public:
enum Base_Type {
base_a,base_c,base_g,base_t,base_invalid
};
ReadIntensity() : bases(base_count) {
}
/// No bounds checking!
inline double getbase(Base_Type position) const {
return bases[position];
}
/// No bounds checking!
inline void setbase(Base_Type position,double value) {
bases[position] = value;
}
const static int base_count = 4;
vector<double> bases;
};
I'm choosing to use an enum here because I feel it represents my
problem well. Sometimes I want to access my bases though name, other
times I'd like to be able to enumerate over the enum. However
iterating over the enum seems messy for example:
#include <vector>
#include <iostream>
using namespace std;
int main() {
ReadIntensity r;
r.setbase(ReadIntensity::base_a, 5.5);
r.setbase(ReadIntensity::base_t, 5.6);
r.setbase(ReadIntensity::base_g, 5.7);
r.setbase(ReadIntensity::base_c, 5.8);
double sum=0;
ReadIntensity::Base_Type i;
for(i = ReadIntensity::base_a;i <
ReadIntensity::base_invalid;i=ReadIntensity::Base_Type (i+1)) {
sum += r.getbase(i);
}
cout << sum << endl;
}
Where I'm basically having to hard code in the ends of my enum. Is
there a better way of attacking this problem?
For example would this be a better solution?
#include <vector>
#include <iostream>
using namespace std;
class ReadIntensity {
public:
static const int base_a = 0;
static const int base_c = 1;
static const int base_g = 2;
static const int base_t = 3;
static const int base_invalid = 4;
static const int num_bases = 5;
ReadIntensity() : bases(num_bases-1) {
}
/// No bounds checking!
inline double getbase(int position) const {
return bases[position];
}
/// No bounds checking!
inline void setbase(int position,double value) {
bases[position] = value;
}
vector<double> bases;
};
int main() {
ReadIntensity r;
r.setbase(ReadIntensity::base_a, 5.5);
r.setbase(ReadIntensity::base_t, 5.6);
r.setbase(ReadIntensity::base_g, 5.7);
r.setbase(ReadIntensity::base_c, 5.8);
double sum=0;
int i;
for(i = 0;i < ReadIntensity::num_bases;i++) {
sum += r.getbase(i);
}
cout << sum << endl;
}
Suggestions and general comments appreciated.