0

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;
}
  • 2
    Like any other vector, your `results` starts out *empty*. Any and all indexing into it will be out of bounds. If you know the size when you define the vector you can set its size then, otherwise you must push back new elements. – Some programmer dude Jul 15 '21 at 19:18
  • 1
    See [Why should I not #include ?](https://stackoverflow.com/q/31816095) and [Why using namespace std is bad practice](https://stackoverflow.com/questions/1452721). – prapin Jul 15 '21 at 20:10
  • Wherever you learned `#include ` ... run as far away from there as possible. – Eljay Jul 15 '21 at 20:18

0 Answers0