Reputation: 1241
I was trying to write a program and I encountered some problem with vector
. I have a logic where the values of the vector
are to be compared at every iteration of the loop. So I initialize the vector and I push one element to each of the vector. Now since I have one element in both of these vectors, I should be able to compare and iterate as the following code should do, but it isn't. There might be a bug, but its difficult to find.
int M = 3; // I am passing values of M and N to this function
int N = 3;
std::vector<int> X;
std::vector<int> Y;
X.push_back(1);
Y.push_back(1);
int x = 0;
for(int i = 1; i <= N; i++){
for(int j = 1; j <= M; j++){
if((X[x] <= i) && (Y[x] <= j)){
if (x > 0){
X.push_back(i);
Y.push_back(j);
x = x + 1;
}
else{
X[0] = 1;
Y[0] = 1;
x = x + 1;
}
}
}
}
for(int i = 0; i < X.size(); i++){
cout << X[i] << "; " << Y[i] << endl;
}
I get the following output with the above program.
`1; 1`
But I need to produce this.
`1; 1`
`1; 2`
`2; 2`
Upvotes: 0
Views: 69
Reputation: 409136
You have undefined behavior.
When x
is zero you don't push a new entry into the vectors, you do however increase x
and the next iteration you access X[1]
and Y[1]
which is out of bounds.
Upvotes: 8