C++ C++;无效指针
我试图解决这个问题: 我很确定这个算法是正确的,但是我在提交的文件中发现了无效的指针错误。 我一直在努力寻找错误,但没有结束。 代码如下:C++ C++;无效指针,c++,pointers,free,C++,Pointers,Free,我试图解决这个问题: 我很确定这个算法是正确的,但是我在提交的文件中发现了无效的指针错误。 我一直在努力寻找错误,但没有结束。 代码如下: #include <iostream> #include <vector> using namespace std; struct node{ int value; vector<struct node*> children; }; void handshakes(int n, struct node
#include <iostream>
#include <vector>
using namespace std;
struct node{
int value;
vector<struct node*> children;
};
void handshakes(int n, struct node *node, long long int &hs, long long int &fb, int height){
if((int)node->children.size() == 0){
hs += height-1;
fb += n - height;
}
else{
for(int i = 0; i < (int)node->children.size(); i++){
handshakes(n, node->children[i], hs, fb, height+1);
}
}
}
int main()
{
int T;
cin >> T;
for(int t = 0; t < T; t++){
int n;
cin >> n;
vector<struct node*> army;
army.resize(0);
for(int i = 0; i < n+1; i++){
struct node *temp = (node * )malloc(sizeof(node));
temp->value = i;
temp->children.resize(0);
army.push_back(temp);
}
int a;
for(int i = 0; i < n; i++){
cin >> a;
for(int j = 0; j < (int)army.size(); j++){
if(army[j]->value == i+1){
army[a]->children.push_back(army[j]);
break;
}
}
}
long long int hs = 0;
long long int fb = 0;
handshakes(n, army[0], hs, fb, 0);
cout << hs << " " << fb/2 << endl;
}
return 0;
}
#包括
#包括
使用名称空间std;
结构节点{
int值;
媒介儿童;
};
无效握手(整数n、结构节点*节点、长整数和hs、长整数和fb、整数高度){
if((int)node->children.size()==0){
hs+=高度-1;
fb+=n-高度;
}
否则{
对于(int i=0;i<(int)节点->children.size();i++){
握手(n,节点->子[i],hs,fb,高度+1);
}
}
}
int main()
{
int T;
cin>>T;
for(int t=0;t>n;
矢量军;
军队。调整大小(0);
对于(int i=0;i值=i;
临时->子对象。调整大小(0);
陆军。推回(临时);
}
INTA;
对于(int i=0;i>a;
对于(int j=0;j<(int)army.size();j++){
如果(陆军[j]->值==i+1){
军队[a]>儿童。推回(军队[j]);
打破
}
}
}
长整型hs=0;
长整型fb=0;
握手(n,陆军[0],hs,fb,0);
coutfor(int i=0;i值=i;
临时->子对象。调整大小(0);
你从来没有构造过temp->children
,所以你没有可以调用resize
的vector
对象。显而易见的解决办法是将malloc
更改为new
什么是“无效指针错误”?我的建议是在带有IDE的系统上开发这个对象,并使用调试器。malloc
不会初始化C++
对象,因此它不适用于复杂类型,如std::vector
,您应该使用new
(或就地构造)。我一直在尝试查找错误,但没有结束。--这表明只需执行“hackerrank”问题并不能教你基本的C++。明显的错误是你使用了 MalOC/,这是你在学习C++时根本不应该考虑的东西。通过阅读同行评议的C++书籍。C++不是你可以通过“Win”学习的语言之一。我正在学习C++,我想我需要读一些更正式的严谨的东西。有什么建议?很难不知道你已经知道的东西。但是绝对不要费心学习前C ++ 11。学习像<代码> UngQuyPPT之类的东西,学习RAII。
for(int i = 0; i < n+1; i++){
struct node *temp = (node * )malloc(sizeof(node));
temp->value = i;
temp->children.resize(0);