AnotherUser
AnotherUser

Reputation: 1353

What list class to use?

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

Answers (2)

fredoverflow
fredoverflow

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

quantdev
quantdev

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:

Upvotes: 2

Related Questions