问题描述
我的代码是用 C++ 实现的图形。我从网站复制了我的代码,但是当我尝试在本地 IDE 上运行它时,它抛出了一个错误。
#include<iostream>
#include<vector>
#include<list>
#define pi 3.14159
#define ll long long
#define pb push_back
#define pf push_front
using namespace std;
class Graph{ // Graph class
int v;
list <int> *l;
public:
Graph(int v)
{
this-> v = v;
l = new list<int>[v];
}
void add_edge (int i,int j)
{
l[i].pb(j);
l[j].pb(i);
}
void show_adj()
{
for(int i = 0 ; i < v ; i++)
{
cout << i << "->";
for(int a : l[i])
{
cout << a << ",";
}
cout << "\n";
}
}
};
int main() // main body
{
Graph g(4);
g.add_edge(7,4);
g.add_edge(7,3);
g.add_edge(3,1);
g.add_edge(4,1); // adding an edge
g.show_adj(); //showing the edges
//vector<int> v;
//int t; cin >> t;
//while(t--)
//{
//
//}
return(0);
}
在抛出 'std::bad_alloc' what() 实例后调用终止:std::bad_alloc
我认为这与内存不足或变量脱离 main()
函数有关,但我不知道如何解决这种特定情况下的问题。如果相关,我正在使用 Windows 计算机。
请帮我找出问题所在。
如果你能发布代码片段,那对我来说会很容易。
解决方法
您创建了一个列表数组,其中有四个列表的空间,然后尝试设置第八个条目的值。那行不通。
List<Object> objects
List<Object> sortedObjects = objects.stream()
.sorted(Comparator.comparing(Object::getAtt().getName)) //this doesn't work.
.sorted(Comparator.comparing(Object::getNumber))
.collect(Collectors.toList());
public class Object {
Attribute att;
int number;
public Attribute getAtt() {
return att;
}
public int getNumber() {
return number;
}
}
public class Attribute {
String name;
public String getName() {
return name;
}
}
因此,这意味着 Graph(int v)
{
this-> v = v;
l = new list<int>[v];
}
Graph g(4);
可以容纳四个编号为 0、1、2 和 3 的列表。
g.l
这会尝试设置 g.add_edge(7,4);
void add_edge (int i,int j)
{
l[i].pb(j);
l[j].pb(i);
}
的值。但 l[7]
是 l[3]
中的最后一个元素。
另外,你确定你想要一个列表数组吗?