Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How compare vector size with an integer? [closed]

Tags:

c++

vector

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.

like image 757
user13107 Avatar asked Jan 30 '13 07:01

user13107


People also ask

Can I compare Size_t with INT?

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.

How do you check the size of a vector in a vector?

vector::size() size() function is used to return the size of the vector container or the number of elements in the vector container.

Does clear change vector size?

clear() function is used to remove all the elements of the vector container, thus making it size 0.

How do you find the length of an INT of a vector?

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.


2 Answers

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;
}
like image 176
Alberto Santini Avatar answered Oct 29 '22 07:10

Alberto Santini


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) {
}
like image 41
billz Avatar answered Oct 29 '22 07:10

billz