[英]Push elements of pointer to array to a std::list in C++
我想我可以只使用一個列表,但此時我只是好奇為什么以下代碼不起作用:
struct treeNode{
char symbol;
double freq;
int left;
int right;
};
treeNode *tree;
int nOS = 16;
tree = (treeNode *)malloc(sizeof(treeNode) * nOS);
list<treeNode> treeList;
初始化樹中的所有元素后,我嘗試將它們推送到樹列表並出現分段錯誤,如果樹是樹節點樹 [nOS],則不會發生,但我正在處理未知數量的元素,所以我需要能夠使用realloc,因此使用 malloc:
for (int i = 0; i < nOS; i++) {
treeList.push_back(tree[i]);
}
我嘗試將 tree[i] 轉換為不同數量的東西:(treeNode),(const treeNode),但我不知道如何讓它工作。 謝謝!
我在ideone中做過這個,它似乎工作:(沒有段錯誤)
#include<list>
#include<vector>
#include <stdlib.h>
#include<iostream>
struct treeNode{
char symbol;
double freq;
int left;
int right;
};
int main(int argc, char** argv)
{
treeNode *tree;
int nOS = 16;
tree = (treeNode *)malloc(sizeof(treeNode) * nOS);
std::list<treeNode> treeList;
std::vector<treeNode> symbolList;
for (int i = 0; i < nOS; i++) {
symbolList.push_back(tree[i]);
}
std::cout << symbolList.size();
};
如果您只想按值(而不是指針)將它們推入列表,則無需malloc
結構。 代碼可以改寫成這樣:
struct treeNode {
char symbol;
double freq;
int left;
int right;
};
int main()
{
const int nOS = 16;
std::list<treeNode> treeList(nOS, treeNode());
std::cout << treeList.size() << std::endl;
return 0;
}
雖然,對於一棵樹,您通常會有指向左/右節點的指針,因此結構將類似於:
struct treeNode {
char symbol;
double freq;
struct treeNode *left;
struct treeNode *right;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.