[英]Inserting values to a vector of vectors in C++ (Graph Problem)
所以這是我的名人問題代碼,這是一個使用向量的圖形問題。
int main()
{
int n;
cin>>n;
int temp;
vector<vector<int>> arr(n,vector<int>(n,0));
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
cin>>temp;
arr[i].push_back(temp);
}
}
for (int i = 0; i < n; i++) //For debugging
{
for (int j = 0; j < n; j++) //For debugging
{
cout << arr[i][j]<<" "; //For debugging
}
cout<<endl; //For debugging
}
int indegree[n]={0},outdegree[n]={0};
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
if (arr[i][j]==1){
outdegree[i]++;
indegree[j]++;
}
}
}
for (int i=0;i<n;i++){
if (indegree[i]==n-1 && outdegree[i]==0){
cout<<"Our celebrity"<<i<<endl;
break;
}
else{
cout<<"-1"<<endl;
break; }
}
return 0;
}
這段代碼給了我錯誤的答案,在通過打印到控制台進行調試后,我發現向量初始化和向該vector of vectors
向量插入值存在一些問題 output 是,
4 //input the value of n-which is size
0 0 1 0
0 0 1 0
0 0 0 0 //the adjacent matrix
0 0 1 0
0 0 0 0
0 0 0 0 //debugged vector of vectors
0 0 0 0
0 0 0 0
-1 //value returned -answer whether the person is a celebrity or not
//if not print -1
我的問題-向量初始化和插入值時犯了什么錯誤? 我該如何改進它?在此先感謝。
線條
cin>>temp;
arr[i].push_back(temp);
向您的向量添加一個新元素。 但是您的向量已經具有正確的大小,您只想設置該值:
cin >> arr[i][j];
i = 0, j = 0 的示例:
最初 arr[0] 是 [0, 0, 0, 0]。 在arr[0].push_back(3)
之后是 [0, 0, 0, 0, 3]。 但是你想要 [3, 0, 0, 0]。 cin >> a[0][0]
將值寫入正確的元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.