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.
If you're going to compare an int type to size_t(or any other library type), you are doing a risky comparison because int is signed and size_t is unsigned, so one of them will be implicitly converted depending on your compiler/platform.
vector::size() size() function is used to return the size of the vector container or the number of elements in the vector container.
clear() function is used to remove all the elements of the vector container, thus making it size 0.
To get the size of a C++ Vector, you can use size() function on the vector. size() function returns the number of elements in the vector.
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;
}
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) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With