Пожалуйста, подпишитесь на официальный канал Codeforces в Telegram по ссылке https://t.me/codeforces_official. ×

Блог пользователя kazuya

Автор kazuya, история, 4 года назад, По-английски

This is a short code which I wrote and it only printed '1' and not "Hello World" but when I did typecasting in if statement i.e if((int) it->second.size() > x) then it worked completely fine. Now if typecasting is the solution then why this line always works " for (int i=0;i < v.size(); i++) ". Please can anyone explain this behaviour ?

Your code here...
#include<bits/stdc++.h>
using namespace std;


int main()
{
    map<int,set<int>> m;
    m[0].insert(1);
    
    int x = -1;
    for(auto it=m.begin();it!=m.end();it++)
    {
        cout<<it->second.size()<<endl;  
        if(it->second.size() > x)
        cout<<"Hello World"<<endl;
    }
}
  • Проголосовать: нравится
  • -2
  • Проголосовать: не нравится

»
4 года назад, # |
Rev. 3   Проголосовать: нравится +23 Проголосовать: не нравится

.size() is unsigned type and x is signed. An operation between 2 different types carries an automatic type conversion. In your case the operation is comparison with the > operator. C++ converts the signed type to unsigned. So -1 will be treated as a very big number.

»
4 года назад, # |
  Проголосовать: нравится +13 Проголосовать: не нравится

Bekh is correct, it's about comparing different types and casting.

Advice for the future: compile with -Wall and always get rid of warnings.

»
4 года назад, # |
  Проголосовать: нравится +31 Проголосовать: не нравится

I have "#define SZ(x) (int)(x).size()" in my macros and it is not to make my typing faster, but to omit all the idiotic shit that can happen when not casting it to signed type.

»
4 года назад, # |
  Проголосовать: нравится +12 Проголосовать: не нравится

std::cout << (-1 > 1u ? "-1" : "1u") << " is greater\n";

-1 is greater