Strange behaviour while using std::vector::size

I m getting an unexpected output for the following code :

#include<bits/stdc++.h>

using namespace std;

#define int long long

int32_t main()

{

    vector <string> d ;

    d.push_back("hh") ;

    d.push_back("jj") ;

    int index = -1 ;

    

    if ( index < d.size()  )

        cout<<"YES"<<endl;

    else 

        cout<<"NO"<<endl;

   

    return 0;

}

The output I get is : NO ( even though index < d.size() )

but when I replace these line from my code :

    if ( index < d.size() )
        cout<<"YES"<<endl;

with the lines below

    int len = d.size() ;
    if ( index < len )
        cout<<"YES"<<endl;

This time the output is as expected : YES

here is the new code which gives expected output :

#include<bits/stdc++.h>

using namespace std;

#define int long long

int32_t main()

{

    vector <string> d ;

    d.push_back("hh") ;

    d.push_back("jj") ;

    int index = -1 ;

    int len = d.size() ;

    if ( index < len )

        cout<<"YES"<<endl;

    else 

        cout<<"NO"<<endl;

   

    return 0;

}

what is reason for the unexpected result I got in the first code ??

vector::size is unsigned, and you are comparing it against a signed int (gcc warns you about this).

I can’t remember the precise rules for promoting integers, but it seems that in this comparison, index is cast to the same type as vector::size, and -1 expressed as an unsigned will be a very large number.

Run this for a little more info:

#include<bits/stdc++.h>

using namespace std;

#define int long long

int32_t main()

{

    vector <string> d ;

    d.push_back("hh") ;

    d.push_back("jj") ;

    int index = -1 ;


    std::cout << "in the comparison 'index < d.size()', index is promoted to:" << static_cast<decltype(d.size())>(index) << endl;

    if ( index < d.size()  )

        cout<<"YES"<<endl;

    else 

        cout<<"NO"<<endl;



    return 0;

}
1 Like

Well, as far as I know, this happens due to the difference in type of two operators.

d.size() has type vector<string>::size_type, whereas the index has type int.

Try comparing the index with some variable like,

vector<string>::size_type var = 100000;
cout << (var > index); // outputs 0
cout << (var < index); // outputs 1
cout << (var == index); // outputs 0

I thought size_type and int were same. but yes probably you are right