Re: std::vector : begin, end and insert - Using Objects instead of ints
On Wed, 11 Apr 2007 03:16:45 -0700, "Nobody" <Nobody@yahoo.com> wrote:
A Test of the emergency broadcast
Readable code here :)
std::vector<CPoint> m_Pts;
I prefer typedef'ing this, something like:
typedef std::vector<CPoint> PointList;
PointList m_Pts;
So you can have e.g. PointList::iterator, which is IMHO more readable,
more elegant and shorter than std::vector<CPoint>::iterator.
std::vector<CPoint>::const_iterator m_cIter;
// *c1_cIter = 200; Error. c1_cIter is constant.
Because: 1) you used a const_iterator [try using iterator if you want
to modify objects]; 2) your iterators are not int's.
m_cIter = m_Pts.begin();
TRACE("Position of Iterator: %d\n", *m_cIter);
This is wrong.
Please understand that *Iter in this case is a CPoint instance (or
reference to instance).
Would you write:
CPoint myPoint;
TRACE("My point is: %d\n", myPoint);
?
I hope you wouldn't.
(Because CPoint is not an int, and the TRACE format specifier is %d,
so for int's.)
For the same reason, your above code with iterator is wrong.
Think the iterator as a kind of "pointer" to vector items.
If you dereference the pointer with operator *, you can access the
pointed vector item.
std::vector<CPoint>::iterator m_Iter;
m_Iter = m_Pts.begin();
TRACE("Position of Iterator: %d\n", *m_Iter);
Error, as above.
for (UINT i = 0; i < m_Pts.size(); i++)
Should be "size_t i = 0...".
{
CPoint& rPt = m_Pts.at(i);
TRACE("Pt[%d] Pt.x %d, Pt.y %d\n", i, rPt.x, rPt.y);
}
This is correct.
You could also avoid the temporary reference, and just write:
TRACE(
"Pt[%d]: x = %d, y = %d\n", i,
m_Pts.at(i).x,
m_Pts.at(i).y
);
for(m_Iter = m_Pts.begin(); m_Iter < m_Pts.end(); m_Iter++)
Better using "++m_Iter".
And "m_Iter != m_Pts.end()"
{
CPoint& pt = m_Pts.at(*m_Iter);
This is wrong.
at() expects the integer position of vector slot.
(e.g. at(0), at(1), at(2), ... at(Size-1))
Do something like this:
for ( m_Iter = m_Pts.begin();
m_Iter != m_Pts.end();
++m_Iter )
{
TRACE("Pt: x = %d, y = %d\n",
(*m_Iter).x, // (*m_Iter) <-> CPoint
(*m_Iter).y
);
}
HTH
MrAsm