Re: std::vector<Point3> -> Access Violation?
On Sat, 18 Apr 2009 14:16:57 +0800, "Jack" <jl@knight.com> wrote:
I strongly believe std::vector is self managed...
How come I get access violation when I did this?
std::vector<Point3> akVertex;
for (int count = 0; count < m_NumOfVerts; count++)
{
PatchVert vert = BoxMesh.getVert(count);
akVertex[count].x = vert.p.x;
...
}
akVertex is NULL when I set breakpoint on it...
What have I done wrong?
Unlike std::map, std::vector items don't come into existence just because
you try to access them. Given that you know the ultimate size before you
enter the loop, you can use:
std::vector<Point3> akVertex(m_NumOfVertsw);
This creates a vector whose size() == m_NumOfVertsw. Equivalently, you
could follow the existing declaration with:
akVertex.resize(m_NumOfVertsw);
Instead of pre-sizing the vector, you could use push_back within the loop,
but that would mean a series of reallocations, which you can avoid by using
reserve, e.g.
std::vector<Point3> akVertex;
akVertex.reserve(m_NumOfVertsw);
// Then to add items to the end of the vector:
akVertex.push_back(item);
The reserve() call makes the vector's capacity() == m_NumOfVertsw but has
no effect on its size(). You really need to understand the difference
between size() and capacity().
--
Doug Harrison
Visual C++ MVP