开发者

Push elements of pointer to array to a std::list in C++

I suppose I could just use a list however, at this point I am just curious why the following code does not work:

struct treeNode{  
    char symbol;  
    double freq;  
    int left;  
    int right;  
};

treeNode *tree;
int nOS = 16;
tree = (treeNode *)malloc(sizeof(treeN开发者_如何学JAVAode) * nOS);
list<treeNode> treeList;

After initializing all the elements in tree I try to push them to treeList and get a segmentation fault, it does not occur if tree is treeNode tree[nOS] but I am working with an unknown number of elements so I need to be able to use realloc, hence the use of malloc:

for (int i = 0; i < nOS; i++) {
    treeList.push_back(tree[i]);
}

I tried casting tree[i] to a various number of things: (treeNode), (const treeNode) but I can't figure out how to get it to work. Thank you!


I have done this in ideone, and it seems to work: (no segfaults)

#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();

};


There is no need to malloc the structs if you are only going to push them into a list by value (instead of pointers). The code could be rewritten to something like this:

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

Although, for a tree, you would usually have pointers to the left/right nodes, so the structure would be something like:

struct treeNode {
    char symbol;
    double freq;
    struct treeNode *left;
    struct treeNode *right;
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜