GlydonNeedsDedication's blog

By GlydonNeedsDedication, history, 3 months ago, In English

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();

»
3 months ago, # |
  Vote: I like it +1 Vote: I do not like it

Check this out: 247667074

Change I made

s += (char)('0' ^ '1' ^ s.back());
s = (char)('0' ^ '1' ^ s[0]) + s;
  • »
    »
    3 months ago, # ^ |
    Rev. 2   Vote: I like it 0 Vote: I do not like it

    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.

    • »
      »
      »
      3 months ago, # ^ |
      Rev. 2   Vote: I like it +1 Vote: I do not like it

      "" 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;
      
»
3 months ago, # |
  Vote: I like it +1 Vote: I do not like it
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 ""