Unwanted behavior of for loop due to vector size used in it

     vector<int>rem;
    for(int i=0;i<rem.size()-1;i++)
     {
             //cout<<rem.size()<<endl;
     }
   I don't know why but the for loop is not stopping, just because the size of vector rem is zero   
   the loop start is not ending. Please do look in this why it is happening?

size function of vector (in your case rem.size() ) returns unsigned integer. Due to which (rem.size() - 1) or (0-1) becomes the maximum value of an unsigned integer data type instead of becoming -1 as in a signed integer data type.

3 Likes

Two remarks: first, size() is unsigned, which may sometimes cause problems. Accordingly, I usually define macros, something like sz© that returns size of C as ordinal signed int. Second, it’s not a good practice to compare v.size() to zero if you want to know whether the container is empty. You’re better off using empty() function.

source : Topcoder You can learn more on STL here.

.size() No-throw guarantee: this member function never throws exceptions.
In best practice use (int) in front of it. Try this one :point_down:

vector<int> v;
     for (int i = 0; i < (int)v.size() - 1; i++){
     	 cout << "a";
     } 
2 Likes