I'm trying to check my 2d array for "blank" spots in the elements but whenever I try to use a comparison operator with one of its elements, the compiler just skips over it. Here's what I mean:
int weight[MAX_CITIES][MAX_CITIES];
1 2 3 4 5 6 7 8 9
for(int i = 0; i < MAX_CITIES; i++){
for(int j = 0; j < MAX_CITIES; j++){
int value = weight[i][j]; // at this point value is 0.
if(weight[i][j] == 0){ // compiler skips this and continues looping
weight[i][j] == NO_ROUTE;
}
}
}
This part of the code comes after I initialize every element in my array to NULL. Even before I initialized every element in the array the compiler skipped the if statement....
Why is my if statement being skipped? How do I check the element at index i,j for a value?
You are misinterpretting what your program is doing. There is no way it is skipping the if statement.
Either the value is not zero like you expect, or you're doing something weird that you shouldn't be. Either way, there is no way to tell what's going wrong from the code you posted. We'd need to see more code.
it is as disch says, i see no logical reason for the code to skip the if statement, other than the value not being 0.
btw am i completely wrong if i say you are doing something wrong inside your if statement? i mean isnt "==" the comparison operator, while "=" is the one for asignment? from your code im guessing you wana assign the value of NO_ROUTE to the array, not compare the two?
Man! C++ does not automatically initialize any value to a variable you define
you have to do yourself! C++ is not QBASIC !
you just define your array int weight[MAX_CITIES][MAX_CITIES];, however you are not setting the elements to any thing!!! first do that and than check its! like this way
1 2
for(int i = 0; i < MAX_CITIES; i++)
for(int j = 0; j < MAX_CITIES; j++) weight[i][j] = 0 ;
first off, I don't understand the use of arrays when you have vectors available - They are dynamically allocating in size, you can access them just as you would an array, you don't have to delete them and worry about memory leaks, you can use iterators on them, etc., etc. For your problem, here you go:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
std::vector<int> first; // one-dimensional vector
std::vector<std::vector<int> > second; // two dimensional vector
unsignedint first_size = 10; // first dimension size
unsignedint second_size = 20; // second dimension size
first.resize(first_size,0); // initialize first array with zero values
second.resize(second_size,first); // initialize 2D array with 1D array values
// for printing out the example
for(unsignedint i = 0; i < second.size(); ++i) {
for(unsignedint j = 0; j < first.size(); ++j) {
std::cout << " " << second[i][j];
}
std::cout << std::endl;
}