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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With