B
Boon
Hello everyone,
Consider a list of integers: 1 2 3 4 5
I want to print every pair (v(i),v(j)) where i < j
With a plain old array, I'd write something along the lines of
#include <stdio.h>
#define N 5
int main(void)
{
int i, j, v[N];
for (i=0; i < N; ++i) v = i+1;
for (i=0; i < N; ++i)
for (j=i+1; j < N; ++j)
printf("(%d,%d)\n", v, v[j]);
return 0;
}
but I need to be able to remove elements in the middle of the list, and
reinsert them later. Therefore, I thought I'd use an std::list.
#include <list>
#include <cstdio>
#define N 5
typedef std::list<int> int_list;
int main(void)
{
int i;
int_list v;
int_list::iterator it1, it2;
for (i=0; i < N; ++i) v.push_back(i+1);
for (it1=v.begin(); it1 != v.end(); ++it1)
for (it2=it1+1; it2 != v.end(); ++it2) // ILLEGAL
^^^^^
printf("(%d,%d)\n", *it1, *it2);
return 0;
}
AFAIU, an std::list iterator is not a Random Access Iterator, thus
"it1+1" is invalid. Is this correct?
How can I say "initialize it2 to something that points to the next
element after that pointed to by it1" ?
For the moment, I've settled for
for (it2=it1, ++it2; it2 != v.end(); ++it2)
but I find it ugly.
Regards.
Consider a list of integers: 1 2 3 4 5
I want to print every pair (v(i),v(j)) where i < j
With a plain old array, I'd write something along the lines of
#include <stdio.h>
#define N 5
int main(void)
{
int i, j, v[N];
for (i=0; i < N; ++i) v = i+1;
for (i=0; i < N; ++i)
for (j=i+1; j < N; ++j)
printf("(%d,%d)\n", v, v[j]);
return 0;
}
but I need to be able to remove elements in the middle of the list, and
reinsert them later. Therefore, I thought I'd use an std::list.
#include <list>
#include <cstdio>
#define N 5
typedef std::list<int> int_list;
int main(void)
{
int i;
int_list v;
int_list::iterator it1, it2;
for (i=0; i < N; ++i) v.push_back(i+1);
for (it1=v.begin(); it1 != v.end(); ++it1)
for (it2=it1+1; it2 != v.end(); ++it2) // ILLEGAL
^^^^^
printf("(%d,%d)\n", *it1, *it2);
return 0;
}
AFAIU, an std::list iterator is not a Random Access Iterator, thus
"it1+1" is invalid. Is this correct?
How can I say "initialize it2 to something that points to the next
element after that pointed to by it1" ?
For the moment, I've settled for
for (it2=it1, ++it2; it2 != v.end(); ++it2)
but I find it ugly.
Regards.