Hello everyone I am having an odd problem, I currently finished a programming challenge from coderbyte. I used visual studio for testing and writing my code and than I copy it to their native environment on coderbyte. When I run the program on visual studio everything works fine and the solution is correct (at least with the test I have). Now when I transfer to coderbyte I am getting a segmentation error on the bool search function, any ideas what the issue might be?
I did some reading on the topic with regards to array/pointer with segmentation debugging and I looked back on my code and everything to me seems logical. here is the code.
// Linear search function to check if a character is currently in that string
bool search(string temp, char letter)
{
for (int x = 0; x < temp.length(); x++)
{
if (letter == temp[x])
{
returntrue;
}
}
returnfalse;
}
// Function that will determine how many unique characters are in the specified string
int uniqueCount(string temp)
{
string uniqueString;
for (int x = 0; x < temp.length(); x++)
{
if ( x == 0 )
{
uniqueString.push_back(temp[x]);
}
elseif (!search(uniqueString, temp[x])) // Insert only the uniquer character into the string
{
uniqueString.push_back(temp[x]);
}
}
return uniqueString.length(); // return the current total number of unique characters
}
string KUniqueCharacters(string str) {
// getting the first character as an integer
int unique = int(str[0]) - 48;
int index = 1;
string temp, temp2;
while (index < str.length())
{
for (int x = index; x < str.length(); x++)
{
temp.push_back(str[x]);
// Condition for when we reach pass the k integer
// delete the last character for that substring
if (uniqueCount(temp) > unique)
{
x--;
temp.erase(temp.end());
// Compare to keep the largest substring
if (temp.length() > temp2.length())
{
temp2 = temp;
}
temp.clear();
}
}
// We compare once more in the case that the substring continues to the end
if (temp.length() > temp2.length())
{
temp2 = temp;
}
temp.clear();
index++;
}
return temp2;
}
here is the exact error I am getting:
bash: line 7: 14231 Segmentation fault (core dumped) ./a.out
line 7 being line 3 in the code sample I posted
Yeah that was the other issued since pop_back correct me if I am wrong only works for C++ 11, the environment they use is an older version. In my ide I utilized the pop_back method though. Also thank you I used the temp.erase(temp.end()-1) and it works as intended.
I thought the temp.end() signified the last character. the same way temp.begin() signifies the beginning character correct?
EDIT:
Ok never mind it seems the end() returns an index/iterator past the last element of a string. Wich makes sense now for the segmentation error I was getting. Again thank you