STL quiz.

2008/02/25

Given A is a vector<int> with a sequence of integer.

int threshold = -1;
if (A.size() > threshold) threshold = A.size();

Indicate any possible error(s) in the above program segment.

廣告

13 回應 to “STL quiz.”

  1. Yun Says:

    Hmm… I will look at it from a math perspective:

    The first line is an invalid declaration. Int threshold can’t be set to -1?!! (integer can’t be negative.)

  2. Justin Says:

    haha, wrong~~

    in gcc, int by default is signed (which means it can be negative)

    but you are close..

  3. Yun Says:

    頂﹐等我仲以為自己好醒添。灰曬!!

    But A.Size() will always be positive… so threshold will need to be positive too?!

    Err… I’m only guessing here, don’t know CS. Haha. 😛

  4. Scorpio Says:

    A.size() returns an unsigned value which can overflow when used in a comparison with -1.

  5. Justin Says:

    Yun: Even I am a CS grad student, i hv spent 15 mins to de this bug tonight!!

    Scorpio: Wow!!!!!! BINGO!!!! u r a econ major, can’t believe you can answer this!

  6. 媽媽阿四 Says:

    so are you trying to get free debugging help here? ; )

  7. Scorpio Says:

    Justin: 你可能以為我係另一位天蠍座吧。我追看你的網誌有一段日子,間中留言,不過你對我應該所知無多。:-) 我本科修的是電腦工程。

  8. Justin Says:

    Scorpio: 咁你係唔係之前留過言既?

    阿四:If i can get free debugging here, there will be 10 posts everyday~~~!!!!

  9. morca Says:

    Perhaps something is amazing that:

    Have you tried (threshold < A.size())?

    I don’t know it works or not, but just my guess.

  10. Scorpio Says:

    Justin: 都話間中留言,梗係之前留過言啦。電郵地址都只係用一個,你應該可以分辨到誰是我誰不是我。

  11. 權權 Says:

    Problem exists between chair and keyboard.

  12. Justin Says:

    Morca: I hv tired this as well, probably g++ does not do any type casting between signed and unsigned of the same type.

    Scorpio: 嗯。我好好記住。

    權:There lies the solution as well.

  13. Scorpio Says:

    If you think about it, g++ was casting the values, which was why you did not get a compile-time error. The problem is that signed integers and unsigned integers have the same width (i.e. 32 bits), and no matter which way you cast the values (either the unsigned large number to a negative signed number, or the signed -1 to the unsigned UINT_MAX), the code would not work as intended.


發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s

%d 位部落客按了讚: