I need to use a list of int[2]. I tried using the list from STL but I’m getting weird results when trying to access the list.
I save all different combinations of [-1,+1] in the list, but when I try to get one of them, it’s always (1,1).
Here is my code:
#include <iostream>
#include <list>
using namespace std;
int main (void){
list<int*> test;
int x=0,y=0,i,j,k,l;
int *pin=new int[2];
for (k = x-1; k <= x+1; k++) {
for (l = y-1; l <= y+1; l++) {
pin[0] = k;
pin[1] = l;
cout<<"inserting into list: "<<k<<" "<<l<<endl;
test.push_back(pin);
}
}
while(!test.empty()){
pin=test.back();
std::cout<<"List contains: "<<pin[0]<<" "<<pin[1]<<std::endl;
test.pop_back();
}
}
You allocate one single pin with
new, and add it multiple times, just changing the values.In other words, you add pin to the list, change it and the existing references to the same pin in the list will also change. In the end, all pin’s in the list will have the value of the last inserted one.