Вопрос

I'm trying to write code that goes through a list of 'pointNodes', and printing the x variable of the current, previous, and next node for each one - expect for the first and last nodes in the list, which use the last node instead of the previous one and the first node instead of the next one respectively.

Here's the code that prints the list:

n = 1;
p = 1;
for (i = pointList.begin(); i != pointList.end(); ++i)
{

    if (i == pointList.begin()) // for the first node, works fine
    {
        cout << "First node! x is " << i->getX() << ", next X var is " << next(point, n)->getX() << ", previous X is " << pointList.begin()->getX() << " (n is(" << n << "), p is(" << p << ")" << endl;
        n = n + 1;
        p = p - 1;
    }
    else if (i == pointList.end()) // problem bit
    {
        cout << "Last node! x is " << i->getX() << ", next X var is " << pointList.begin()->getX() << ", previous X is " << prev(point, p)->getX() << " (n is(" << n << "), p is(" << p << ")" << endl;
        n = n + 1;
        p = p - 1;
    }
    else // for everything inbetween, works fine.
    {
        cout << "x is " << i->getX() << ", next X var is " << next(point, n)->getX() << ", previous X is " << prev(point, p)->getX() << " (n is(" << n << "), p is(" << p << ")" << endl;
        n = n + 1;
        p = p - 1;
    }



}

I realise that list.end doesn't actually mean the last node in the list. I'm still not sure how to do something different for that last node though, so I'd appreciate any help. I've tried "if (pointList.back())" instead, but that gives me a "no operator matches these operands" error.

Thanks!

Это было полезно?

Решение 3

Q: I've tried "if (pointList.back())" instead, but that gives me a "no operator matches these operands" error.

The problem with that approach is you need to compare the iterator against the last element, and not just check if the last element in the list is zero or not.

The better approach would be is to check if the iterator points to the "end -1" as follows:

else if (next(i) == pointList.end())

Note that std::next was only introduced in C++11, so without support for that, you would need to create the semantics yourself or just use boost::next.

Другие советы

I think your cleanest solution checks that there are more than two elements and then simply iterates over the range begin+1 up to end-1:

// check size, otherwise increment/decrement might be invalid
if (list.size() < 2) return;

for(it = std::next(container.begin()), end = std::prev(container.end()); it!=end; ++it)
{
    prev = std::prev(it);
    next = std::next(it);
    // output prev, it, next here
}

Given that your list contains enough elements, it might be a start to fix the second condition to test for the last valid element, i.e., the one before end():

else if (std::next(i) == pointList.end()) // fixed problem bit
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top