Reputation: 1353
I'd like to create a short lived list, over the life of a function, to collect a list of CPoint
objects and then iterate over those objects. I'd like to use CTypedPtrList
but I am not sure how to set it up to have it accept objects not derived from CObject
; CPoint
comes from a struct tagPOINT
.
Is it possible to use CTypedPtrList
with CPoint
?
Otherwise, should I just use std::list<CPoint>
? // I have started to use std:list
and can successfully build a list, but I cannot find a way to iterate over the list.
std::list<CPoint*> pointList;
// Add to the list with list.push_front(new CPoint(x, y));
std::for_each(pointList.begin(), pointList.end(), [](pointList* cur)
{
TRACE("APoint: %f, %f\n", cur->x, cur->y);
});
I have tried that, but I keep getting told that for_each
is not a member of std
. I tried to add #include <for_each>
(as I had to do for list
) but it still is not recognized.
Any suggestions?
Upvotes: 0
Views: 111
Reputation: 263118
I recommend a std::vector
. Also, there is no need for pointers here:
std::vector<CPoint> pointList;
// ...
pointList.emplace_back(x, y);
// ...
for (const CPoint& p : pointList)
{
TRACE("APoint: %f, %f\n", p.x, p.y);
}
You seem to be using a very old C++ compiler. Try the following:
std::vector<CPoint> pointList;
// ...
pointList.push_back(CPoint(x, y));
// ...
for (std::vector<CPoint>::const_iterator it = pointList.begin();
it != pointList.end(); ++it)
{
TRACE("APoint: %f, %f\n", it->x, it->y);
}
Upvotes: 3
Reputation: 23793
To fix your compilation error, #include <algorithm>
and change to :
std::for_each(pointList.begin(), pointList.end(), [](CPoint* cur)
{ ^^^^^^^^
TRACE("APoint: %f, %f\n", cur->x, cur->y);
});
Or more simply with a for range loop:
for(auto& p : pointList)
{
TRACE("APoint: %f, %f\n", p->x, p->y);
}
Note:
As for choosing a container Stick to Standard containers as long as you can, std::list<>
is a good choice if you need a doubly linked list, but in your case an std::vector<>
might just do it as well.
Also see In which scenario do I use a particular STL Container?
Upvotes: 2