user13107 user13107 - 1 year ago 80
C++ Question

How compare vector size with an integer?

I am using the following code to throw an error if the size of vector (declared as

vector<int> vectorX
) is is different than intended.

vector<int> vectorX;
int intendedSize = 10;
// Some stuff here
if((int)(vectorX.size()) != (intendedSize)) {
cout << "\n Error! mismatch between vectorX "<<vectorX.size()<<" and intendedSize "<<intendedSize;

statement shows the same size for both. The comparison is not showing them to be equal.

Output is
Error! mismatch between vectorX 10 and intendedSize 10

Where is the error? Earlier I tried
(unsigned int)(intendedSize)
but that too showed them unequal.

Answer Source

You are missing ) in the right side of if statement

if((int)(vectorX.size()) != (intendedSize)) {

But note, it's bad to cast return value of std::vector::size to int. You lose half of the possibilities of what the size could be(thanks to chris).

You should write:

size_t intendedSize = 10; 
// OR unsign int intendedSize  = 10; 
if(vectorX.size() != intendedSize) {