I'm trying to do a double-loop over a std::list to operate on each pair of elements. However, I'm having some trouble initialising the second iterator. The code I'd like to write is:
for(std::list<int>::iterator i = l.begin(); i != l.end(); ++i) {
for(std::list<int>::iterator j = i+1; j != l.end(); ++j) {
...
}
}
That doesn't work because list iterators aren't random-access, so you can't do +1. But I'm having some trouble finding a neat alternative; the compiler doesn't seem to be very happy with std::list<int>::iterator j(i)++;
which I had some hope for. Achieving what I want seems like I'm going to have to have some awkward extra increment which won't fit the structure of the for loop nicely.
There are obvious alternatives (using a vector, for example!) but it seems to me that there should be some reasonably neat way of doing this which I'm just not seeing at the moment.
Thanks in advance for any help :)
Adding iterators to your containers will make them compatible with the range-based for loops and the C++ Algorithms library: a collection of functions for searching, sorting, counting and manipulating containers, based on iterators.
An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualised as something similar to a pointer pointing to some location and we can access content at that particular location using them.
for(std::list<int>::iterator i = l.begin(); i != l.end(); ++i) {
std::list<int>::iterator j = i;
for(std::advance(j, 1); j != l.end(); ++j) {
...
}
}
How about:
for (std::list<int>::iterator i = l.begin(); i != l.end(); ++i) {
for (std::list<int>::iterator j = i; ++j != l.end(); ) {
// ...
}
}
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