我构建了一个程序,用于将多图转换为无向图,并使用邻接列表作为图表示来删除多个边和自环。`
#include<iostream>
#include<istream>
#include<algorithm>
#include<list>
using namespace std;
int main()
{
list<int> adj[3];
list<int> auxArray[3];
list<int> adjnew[3];
cout<<adjnew[2].back()<<endl; // Gives output 0, whereas it should have some garbage
//value
for(int i = 0;i<3;i++){
int x;
while(true){ // reading a line of integers until new line is encountered , peek()
returns the next input character without extracting it.
cin>>x;
adj[i].push_back(x);
auxArray[i].push_back(x);
if(cin.peek() == '\n') break;
}
}
//flatten the adj-list
for(int i = 0;i<3;i++){
list<int>::iterator it = adj[i].begin();
while(it != adj[i].end()){
auxArray[*it].push_back(i);
it++;
}
}
for(int i = 0;i<3;i++){
list<int>::iterator it = auxArray[i].begin();
while(it != auxArray[i].end()){
//cout<<*it<<" "<<adjNew[*it].back()<<endl;
if((*it != i) && ((adjnew[*it].back()) != i)){
// cout<<*it<<" -> "<<i<<endl;
adjnew[*it].push_back(i);
}
it++;
}
}
for(int i = 0;i<3;i++){
list<int>::iterator it = adjnew[i].begin();
while(it != adjnew[i].end()){
cout<<*it<<" ";
it++;
}
cout<<endl;
}
return 0;
}
`
但它显示St9bad_alloc错误,而我的列表大小仅为 3。
此外, adjnew[2].back() 没有被初始化就被赋值为“0”,而它应该有一些垃圾值。
'
Input:
1 2 1
0
1 1
Output of Program(Incorrect because of 0 as back element in adjnew[2]):
1 2
0 2
1
Correct Output:
1 2
0 2
0 1
'
欢迎所有建议!