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

Автор spkumar9952, 23 месяца назад, По-английски

Hello Codeforcers! I would like to share something which I had experienced in one of the contest.

Never use .size()-x in C++. Because the size() method returns the unsigned int value, So if the vector is empty and you try to subtract x from the value, then instead of giving -x it will give max value of unsigned int (Cyclic way).

It will lead to lots of problems. For example, if you use in for loops it will crash the program.

for(int i=0; i < vec.size()-1; i++){
    // it will run unsigned max times if the vector is empty!
}

it is also same for all inbuilt data structures in C++ (string, stack,...). To avoid this, typecast the size into int. Example: int(vec.size())-1 or (int)vec.size()-1. Another way is store in int variable and subtract value from it.

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится