Help! weird case

Hi,

I build a class with some vectors, with interrelations. Then I use this class to build some objects. However, when I compile, sometimes the VS 2010 said "vector subscript out of range", sometimes it works fine. Please see the following codes of class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class CAgent
{
public:
	// declare some vectors
	std::vector<double> theta;
	std::vector<double> r;
	std::vector<double> s_hat;
	std::vector<double> mu;
	// declaration continues...

	// constructor
	CAgent(double ini_theta, double rf, double ini_s, double mu0, double alpha, double beta, double delta, double w, double c, double eta, double D, double F):
	theta(1, ini_theta), r(1, rf), s_hat(1, ini_s), mu(1, mu0+alpha*pow(ini_s, beta)), p(1, 1+mu[0]*(r[0]+delta+w/theta[0]+c/eta)), d(1, ini_s* D/p[0]),Y_hat(1,ini_s*D/theta[0])
	{};
};


From here when I build objects on this class in main function, it works fine. However, for the last vector definition "Y_hat", if I use

Y_hat(1,ini_s*D/mu[0])
or
Y_hat(1,ini_s*D/d[0])

while compiling the VS 2010 said "vector subscript out of range".

All vectors in the class are defined in the same way. How is it possible when I use element of one vector it works, and for another vector it doesn't work? Could someone help me please?

Thanks a lot.
Apparently constructor of Y_hat is called before mu and d are constructed. Members are initialized in the order they are declared and not in the order you write in the initializer list. In this case it would be best to write the initialization in the constructor body to avoid such hard to notice problems. It would be more readable too.
Thanks for your help! I didn't pay attention to that part.

Is there anyway to make it possible to separate the influence of declaration order on initializer list? Because I have a lot of vectors to declare, and a lot of interrelations between them in initialization. If I declare and initialize all together, it will be easy to make mistakes.

Thanks again!
Do initialization in constructor body. Then you can order it as you like. Initialization lists are not well suited for members that depend on one another. Nothing can be done about it.
I get it, that helps. Thanks!
Just wondering whether it might be better with a class containing: theta, r, s hat, mu etc. Then have a vector of the class objects.

Would this make it much easier all round?

The analogy I am thinking of is like with a 3d point, you would have :

1
2
3
4
5
6
7
8
class Point3D {
double x;
double y;
double z

};

std::vector<Point3D> PointVector;



As opposed to to:

1
2
3
4
5
Class Points {
std::vector<double> x;
std::vector<double> y;
std::vector<double> z;
};


I am wondering whether my analogy is right - does my idea sound better for your problem?

HTH
Topic archived. No new replies allowed.