0

I am confused with C++ vector and ask for help. I declare a class CBoundaryPoint:

class CBoundaryPoint:
{
public:
    double m_param;
    int m_index;    
}

And then I define a vector:

vector<CBoundaryPoint> vBoundPoints;
CBoundaryPoint bp;
double param;
// other codes
bp.m_param = param;
vBoundPoints.push_back( bp );

It surprises me that for every element in vBoundPoints, the value of m_param is totally different from the given value param. I just don't know why.

For Example:

param = 0.3356;
bp.m_param = param; // so bp.param equals to 0.3356;
vBoundPoints.push_back( bp ); // while (*(vBoundPoints.end()-1)).m_param = -6.22774385622041925e+066;  same case to other elements

So what happened and why? I'm using VS2010.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
tlanyan
  • 3
  • 1
  • Could you add some code to show how you are checking the values? – juanchopanza Aug 02 '12 at 14:25
  • Yeah, you want to probably use .rbegin () or better yet .back () instead of .end () - 1 – vmpstr Aug 02 '12 at 14:28
  • 1
    Please give a short, complete code example that demonstrates the problem. – Benjamin Lindley Aug 02 '12 at 14:28
  • 1
    Your code should work, the reason it doesn't is that you've made a mistake somewhere in the code you haven't posted. – john Aug 02 '12 at 14:29
  • The cool thing is that if I do .resize() the vector to exactly number of elements in the vector, then end()-1 gives the proper value.. but if I .resize() the vector to something larger, then it gives me a garbage value :D as expected. I've learned something today! – vmpstr Aug 02 '12 at 14:31

1 Answers1

1

You probably get garbage when you resize the vector or create a vector of a certain size using the size_type constructor. You get default-constructed objects in your vector, and these contain primmitive types. Since you have no user defined default constructor, the values are essentially random, or "garbage".

You can fix this by adding a default constructor to your class:

class CBoundaryPoint:
{
public:
    CBoundaryPoint : m_param(), m_index() {} // initializes members to 0. and 0
    double m_param;
    int m_index;    
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480