Search code examples
c++xcodeclassvectorexc-bad-access

Problems with two-dimensional vector in c++


I'm trying to write a class in c++, that presents a group of people (each person has its own row), and the numbers in the rows represent this person's friends. If person a is person's b friend, then the person b is person's b friend as well. I came up with something like this:

class Friends {
public:
    Friends(int n);
// Creates a set of n people, no one knows each other.
    bool knows(int a, int b);
// returns true if the 2 people know each other 
    void getToKnow(int a, int b);
// Person a & b meet.
    void mutualFriends(int a, int b);
// cout's the mutual friends of person a & b
    void meeting(int a);
//all friends of person a also become friends
    int max();
//return the person with the highest number of friends

private:
    vector<vector<int>> friends;
};

Friends::Friends(int n) {
    vector<vector<int>> friends;
}

bool Friends::knows(int a, int b) {
    for(int i=0; i<friends[a].size(); i++) {
        if (friends[a][i]==b) {
            return true;
        }
    }
    return false;
}

void Friends::getToKnow(int a, int b) {
    friends[a].push_back(b);
    friends[b].push_back(a);
}

void Friends::mutualFriends(int a, int b) {
    for (int i=0; i<friends[a].size(); i++) {
        for (int j=0; j<friends[b].size(); j++) {
            if (friends[a][i]==friends[b][j])
                cout << friends[a][i] <<", ";
        }
    }
}

void Friends::meeting(int a) {
    for (int i=0; i<friends[a].size(); i++) {
        for(int j=0; j<friends[a].size();j++) {
            if(i!=j && i!=a && j!=a) {
                getToKnow(i,j);
            }
        }
    }
}

int Friends::max() {
    int maks = 0;
    for (int i=0; i<friends[i].size(); i++) {
      if (friends[i].size()<friends[i+1].size())
          maks = i;
    }
    return maks;
}

int main() {
    Friends f1 (4);
    f1.getToKnow(1,3);
}
   

So far, every time I try to add something to the vector (f.e. with the function getToKnow) the compiler can't compile the program, pointing that

friends[a].push_back(b);
friends[b].push_back(a);

is wrong. The exact information displayed is "Thread 1: EXC_BAD_ACCESS (code=1, address=0x20)". I don't know what I'm doing wrong and if I'm using the 2d vector correctly.


Solution

  • In the line

    Friends::Friends(int n) {
        vector<vector<int>> friends;
    }
    

    you are creating a local vector of vectors which will be deallocated upon leaving the function.

    What you are looking for is:

    Friends::Friends(int n) {
        friends.resize(n);
    }
    

    Which will allocate n vectors, allowing you to access any element below that threshold.