I am having a segmentation fault while running this code:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
class cipher {
public:
char letter;
int frequency;
};
bool comp(const cipher &A, const cipher &B) {
if(A.frequency<B.frequency)
return true;
else
return false;
}
vector<cipher> cipherF;
int posOf(char c)
{
int i;
for(i=0; i<26; ++i)
if(cipherF[i].letter == c)
return i;
return -1;
}
int main()
{
int t;
cin >> t;
string tmp;
getline(cin, tmp);
while(t--) {
cipherF.clear();
for(int i=97; i<=122; ++i)
{
cipher cip;
cip.letter = i;
cip.frequency = 0;
cipherF.push_back(cip);
}
string txtF, cipherText;
getline(cin, txtF);
getline(cin, cipherText);
for(int i=0; i<cipherText.size(); ++i)
{
char c = tolower(cipherText[i]);
++(cipherF[c-97].frequency);
}
stable_sort(cipherF.begin(), cipherF.end(), comp);
for(int i=0; i<cipherText.size(); ++i)
{
int pos = posOf(cipherText[i]);
if(pos == -1)
continue;
else if(isupper(cipherText[i]))
cipherText[i] = toupper(txtF[pos]);
else
cipherText[i] = txtF[pos];
}
cout << cipherText << endl;
}
}
The problem is when I run it in GDB, the code runs fine and excellent. Why is this running in GDB without any segmentation fault, but running at every other place with a segmentation fault?
Here is the problem I am trying to solve: http://www.codechef.com/DEC13/problems/CHODE