求教:代碼運行后出現以下錯誤
vector越界

輸入是這樣的
Input size: 3
1 2 4 3 5 0
2 1 4 0
3 1 5 0
1 2 3
1 2 3
#include <iostream>
#include <vector>
#include <utility>
#include <queue>
using Edge = std::pair<int, int>;
using Node = std::pair<int, std::vector<Edge>>;
class Graph
{
public:
Graph(int size);
~Graph();
public:
void read();
void print(int type);
void getMinLen(int src, int obj, int edge = 0);
private:
void dfs(int point);
void bfs(int point);
bool allUsed();
public:
const int TYPE_DFS;
const int TYPE_BFS;
private:
Node* data;
bool* used;
int size;
int minLen;
};
int main()
{
int size;
std::cout << "Input size: ";
std::cin >> size;
Graph graph(size);
graph.read();
graph.print(graph.TYPE_DFS);
graph.print(graph.TYPE_BFS);
graph.getMinLen(1, 5);
return 0;
}
Graph::Graph(int size) : size(size), TYPE_DFS(0), TYPE_BFS(1), minLen(0x3f3f3f3f)
{
data = new Node[size];
used = new bool[size]();
}
Graph::~Graph()
{
delete[] data;
}
void Graph::read()
{
for (int i = 0; i < size; i++)
{
std::cin >> data[i].first;
int connect, weight;
while (std::cin >> connect, connect != 0)
{
std::cin >> weight;
data[i].second.push_back(std::make_pair(connect - 1, weight));
}
}
}
void Graph::print(int type)
{
for (int i = 0; i < size; i++)
{
if (!used[i])
{
if (type == TYPE_DFS)
{
dfs(i);
}
else if(type == TYPE_BFS)
{
bfs(i);
}
else
{
std::cout << "No this type" << std::endl;
return;
}
}
}
for (int i = 0; i < size; i++)
{
used[i] = false;
}
std::cout << std::endl;
}
void Graph::dfs(int point)
{
used[point] = true;
std::cout << data[point].first << " ";
for (int i = 0; i < data[point].second.size(); i++)
{
if (!used[data[point].second[i].first])
{
dfs(data[point].second[i].first);
}
}
}
void Graph::bfs(int point)
{
std::queue<int> q;
q.push(point);
while (!q.empty())
{
point = q.front();
q.pop();
if (!used[point])
{
used[point] = true;
std::cout << data[point].first << " ";
for (int i = 0; i < data[point].second.size(); i++)
{
q.push(data[point].second[i].first);
}
}
}
}
void Graph::getMinLen(int src, int obj, int edge)
{
used[src - 1] = true;
if (src == obj)
{
minLen = minLen < edge ? minLen : edge;
}
else if(!allUsed())
{
for (int i = 0; data[src - 1].second[i].first != obj - 1; i++)
{
if (!used[data[src - 1].second[i].first])
{
getMinLen(data[src - 1].second[i].first + 1, obj, edge + data[src - 1].second[i].second);
used[data[src - 1].second[i].first] = false;
}
}
}
}
bool Graph::allUsed()
{
for (int i = 0; i < size; i++)
{
if (!used[i])
{
return false;
}
}
return true;
}
uj5u.com熱心網友回復:
主要問題是第三個函式getMinLen報錯越界,前兩個沒問題轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/213050.html
標籤:C++ 語言
上一篇:求助again
下一篇:++算的
