我试着用c++写一个类,它代表一群人(每个人都有自己的行),行中的数字代表这个人的朋友。如果人a是人b的朋友,那么人b也是人b的朋友。我想到了这样的东西:
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);
}
到目前为止,每次我尝试向向量添加内容(例如,使用函数getToKnow)时,编译器都无法编译程序,
friends[a].push_back(b);
friends[b].push_back(a);
错误。显示的确切信息为“线程1:EXC_BAD_ACCESS(代码=1,地址=0x20)"。我不知道我做错了什么,我是否正确地使用了2d矢量。
2条答案
按热度按时间1aaf6o9v1#
排队
你正在创建一个向量的局部向量,它将在离开函数时被释放。
您正在寻找的是:
它将分配
n
向量,允许您访问低于该阈值的任何元素。6psbrbz92#
这里我只是***猜测***,但是你可能应该创建一个 constructor initialize list 来设置成员变量的大小: