0

グラフ表現として adjacency-list を使用して、マルチグラフを複数のエッジと自己ループが削除された無向グラフに変換するプログラムを作成しました。`

 #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;
}

`

しかし、リストのサイズがわずか3であるのに、 St9bad_allocエラーが表示されます。

また、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

'

すべての提案を歓迎します!

4

1 に答える 1

0

cout<<adjnew[2].back()<<endl;

at begin は、空のコンテナでの未定義の動作です。

valgrind が与える

Conditional jump or move depends on uninitialised value(s)

この行の場合:

if ((*it != i) && ((adjnew[*it].back()) != i))

空のコンテナーでの未定義の動作です。

ヒント: operator [] の代わりに container.at() を使用して範囲チェックを行うことができます。

于 2013-08-17T11:29:34.960 に答える