Hello Grime,
The ".size()" function returns a "size_t" which is an "unsigned" something. The "something" will depend on the header files that are used to your compiler.
With the given code the vector is empty with a size of zero. So,
nums.size() - 1
or
0 - 1
is -1. Unsigned numbers can nor be negative.
On my computer I did this:
1 2
|
size_t ans{};
std::cout << ans - 1;
|
And when it ran I got this output:
4294967295
. I believe what happened is that it changed the negative number into the largest possible positive that an "unsigned int" could hold.
At least this time the "size_t" is a type def for an "unsigned int", but not always the case.
For what you need the code would be better written as:
1 2 3 4 5 6
|
std::vector<int> nums;
for (size_t i = 0; i < nums.size(); ++i)
{
std::cout << nums[i]);
}
|
Removing the "- 1" in the for loop will work better especially if the vector is empty.
The ".at(i)" is extra work that is not needed. The for loop will keep you from going past the end of the vector, so all you need is
nums[i];
.
Give that a try and see what happens. You should just by pass the for loop.
Andy