I'm new to C++ and I got a segementation fault error with the following code. I thought that the problem was the way I declared the <vector<vector> matrix but it's not that, I guess. Can anyone please explain where is my mistake?
#include <bits/stdc++.h>
using namespace std;
bool checkAnagram(string a, string b)
{
sort(a.begin(), a.end());
sort(b.begin(), b.end());
if(a == b)
return true;
return false;
}
vector<vector<string>> groupAnagrams(vector<string> words) {
int line = 0, column = 0;
vector<vector<string>> results;
int n = words.size();
for(int i = 0; i < n; ++i)
{
results[line].push_back(words[i]);
for(int j = i + 1; j < n; ++j)
{
if(checkAnagram(words[i], words[j])){
results[line].push_back(words[j]);
words.erase(words.begin() + j);
--n;
--j;
}
}
++line;
}
return results;
}
int main()
{
vector<string> words = {"yo", "act", "flop", "tac", "foo", "cat", "oy", "olfp"};
vector<vector<string>> results = groupAnagrams(words);
for(int i = 0; i < results.size(); ++i)
{
for(int j = 0; j < results[i].size(); ++j)
cout << results[i][j] << ' ';
cout << endl;
}
return 0;
}