Cplusplus.com says the last end of std :: string "will not be dereferenced"

I wish you could clarify some kind of confusion for me. I wrote a function that removes duplicate characters in a string, for example. "AB →" AAABB ".

void remove_dups(std::string& str) { 
    std::string::iterator it = str.begin();
    while (it != str.end()) {
        if (*(it+1) == *it) {
            str.erase(it+1);
        } else {
            ++it;
        }
    }
} 

It seems to work when I test it. However, I was wondering, shouldn't there be a problem with the fence? When "it" is the end of a line, the if statement looks at the next non-existent character. According to cplusplus.com,

The designated end is the theoretical character that will follow the last character in the string. This should not be dereferenced. ( http://www.cplusplus.com/reference/string/string/end/ )

, , fencepost. (, , n00b.)

void remove_dups(std::string& str) { 
    std::string::iterator it = str.begin();
    while (it != str.end()) {
        if ((it+1) != str.end() && *(it+1) == *it) {
            str.erase(it+1);
        } else {
            ++it;
        }
    }
} 

.

+4
3

, ,

Undefined , , . , , . , undefined \0, .

fencepost

, -

if (it != str.end()) {
  ++it;
  while (it != str.end()) {
    /* compare *it and *(it-1) */
  }
}

, erase . , 20 . , 20 . , :

void remove_dups(std::string& str) { 
  std::string::iterator src = str.begin();
  std::string::iterator dst = str.begin();
  if (src != str.end()) {
    ++src;
    ++dst;
    while (src != str.end()) {
      if (*src != *(src-1)) {
        *dst = *src;
        ++dst;
      }
      ++src;
    }
    str.resize(dst - str.begin());
  }
}

, , erase , .

+2

, . , , , . , , ,...

, , non sequence string:: erase , , .

+1

I think the cleanest solution is to stop at the end of the line (the last character of the line), since at this point no further action is taken.

Therefore, it while (it != str.end())should be while (it != str.end() && it != (str.end() - 1)).

0
source

All Articles