How to compare vector size with integer?

I use the following code to throw an error if the size of the vector (declared as vector<int> vectorX ) is different from the intended one.

 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; exit(1); } 

The cout operator shows the same size for both. Comparison does not show that they are equal .

Output Error! mismatch between vectorX 10 and intendedSize 10 Error! mismatch between vectorX 10 and intendedSize 10

Where is the mistake? I tried (unsigned int)(intendedSize) before, but that also showed them uneven.

+4
source share
3 answers

You are missing ) on the right side of the if statement

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

But note that the bad value of the return value is std :: vector :: size for int. You lose half the possibilities of what might be size (thanks to chris).

You must write:

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

I am writing this answer because the other two, including the accepted one, are wrong. The type std::vector size() not unsigned int , not size_t .

The size type of std::vector<T> is equal to std::vector<T>::size_type .

What is it. In some architectures and for some compilers, this may be the same as size_t , but in some others it may not. The assumption that a variable of type size_t may contain the same values โ€‹โ€‹as one of the types std::vector<T>::size_type may fail.

To check that your vector is the right size, you can do something like:

 if(vec.size() != static_cast<std::vector<int>::size_type>(expected_size)) { std::cerr << "Error!" << std::endl; } 
+14
source

Use size_t type to store collection sizes:

 vector<int> vectorX; size_t intendedSize = 10; // Some stuff here if(vectorX.size() != intendedSize) { ... } 

Actually, technically you should use vector<int>::size_type , but in practice it is always a typedef for size_t

An int usually a signed 32-bit integer.

size_t typically an unsigned 64-bit integer (in 64-bit architectures) or a 32-bit unsigned integer (in 32-bit architectures).

(Note that the standard does not apply these restrictions. ABI indicates this, for example, ABI x86 and x86-64).

+2
source

All Articles