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;
}
}
}
.