Reputation: 85
I am trying to get the data already assigned in the list, and if the data is <= -1 then the list must be shown as empty, otherwise print the assigned data.
But, the problem is that my code prints the list is empty.
I think it should print [ +2 ]
instead of an empty list.
Code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <int> number{+2};
char selection{};
do{
cout << "\nMain Menu" << '\n';
cout << "P - Print numbers" << '\n';
cout << "Q - Quite the program" << '\n';
cout << "------------------------" << '\n';
cout << "Enter your Choice: ";
cin >> selection;
if(selection == 'p' || selection == 'P')
{
if (number.size() <= -1)
cout << "[] - The list is Empty" << '\n';
else{
cout << " [ ";
for(int num:number)
cout << num;
cout << " ] " << '\n';
}
}
}while (selection != 'q' && selection != 'Q');
return 0;
}
Upvotes: 0
Views: 147
Reputation: 41474
std::vector::size()
returns an unsigned integer (because the size of a vector can never be negative, and if it returned a signed integer it couldn't refer to as large a range of sizes). When you compare a signed integer (like -1) with an unsigned integer, the signed integer is converted to unsigned for the comparison. -1 converted to an unsigned integer is the largest unsigned integer. This effectively means that you're checking whether the size is no greater than the largest possible size, which is always true.
In any case, if the vector is actually empty, its size will be zero. That's what you should be comparing to, not -1.
Upvotes: 2