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

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

for the Problem 1849C

The SOLUTION I wrote, it is having some out of bounds error in the below code portion.

    s += (char)('0' ^ '1' ^ s.back());
    s = ("" + (char)('0' ^ '1' ^ s[0])) + s; // this line giving error 'out of bounds' though working fine in LOCAL
    n = s.size();

I am not able detect the exact reason.

Same purpose If I try to do like below, its working as expected

// working as expected
    s += (char)('0' ^ '1' ^ s.back());
    reverse(all(s));
    s += (char)('0' ^ '1' ^ s.back());
    reverse(all(s));
    n = s.size();

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

»
9 месяцев назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится

Check this out: 247667074

Change I made

s += (char)('0' ^ '1' ^ s.back());
s = (char)('0' ^ '1' ^ s[0]) + s;
  • »
    »
    9 месяцев назад, # ^ |
    Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

    Thanks, I included the empty string just to make sure the first portion of what we have is a string, as I wasn't sure char to string concat is available.

    still do not get why it was an "out of bound" error, I mainly want to understand the reason to avoid the same kinda mistake in the future.

    • »
      »
      »
      9 месяцев назад, # ^ |
      Rev. 2   Проголосовать: нравится +1 Проголосовать: не нравится

      "" is not actually string, it is const char *. And when you do "" + 'a', you're actually adding ASCII value of 'a' to const char * which is pointer arithmetic, you didn't make a new "a".

      But you have done "Code" + str where std::string str = "Forces"; before and it worked?

      It is because std::string is a class and it can override + and += operator to concatenate string with const char * and choose not to do pointer arithmetic.

      Try running the following code, and you'll get junk output or compiler warning, depending upon flags you are using.

      string x = "" + 'a';
      cout << x << endl;
      
»
9 месяцев назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится
char c = '0';
"" + c; // what that do?

"" is const char*. And you summarize it with 0 symbol which value is 48. So "" + c is pointer to 48-th symbol of ""