I’m writing a piece of code that’s supposed to grow a vector to a certain size. For some reason, the boolean check within the while loop is acting strangely.
Here’s the code that I ran; the first loop doesn’t run like it’s supposed to, but the second one does. To my knowledge, they should both do the exact same thing. What’s going on?
#include <iostream>
#include <vector>
using std::cout;
using std::vector;
int main()
{
int index = 0;
vector<int> vec = {};
//Loop 1
while (index > (vec.size() - 2))
{
cout << "Visiting loop 1n";
vec.push_back(vec.size());
}
bool test = (index > (vec.size() - 2));
//I added this here because I noticed that it is initializing
//as false, even though 0 > -2 is true. In fact,
//when I type "p index > (vec.size() - 2)" in the debugger,
//it says true, but when I type "p test", it says false. Why?
vec = {};
//Loop 2
int compValue = vec.size() - 2;
while (index > compValue)
{
cout << "Visiting loop 2n";
vec.push_back(vec.size());
compValue = vec.size() - 2;
}
return 0;
}