C++ – How compare vector size with an integer?

cvector

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

The cout 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.

Best Answer

I'm writing this answer because the other two, including the accepted one, are both wrong. The type of std::vector's size() is not unsigned int, nor it is size_t.

The type of the size of an std::vector<T> is std::vector<T>::size_type.

That's it. On some architecture and for some compilers it might be the same as size_t, in some others it might not. The assumption that a variable of type size_t can hold the same values than one of type std::vector<T>::size_type can fail.

To check that your vector has the right size you could do something like:

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