| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Hi guys,
I have an urgent problem to solve in c++ as described below.. Any help rendered is greatly appreciated! I have to read in a random amount of nodes(about 10,000), with coordinates x, y, and z from a text file. How can i link up all the nodal information properly so that I can allocate memory efficiently? The best I have thought of is to use a data structure like the one below: struct { float x,y,z; }Node; I do not know if these is the best, as I heard of dynamic data allocation, but really, I do not know the best way to implement it. can someone enlighten me on how I can reference these nodes above? After storing the above nodal information, I will like to reference them in this manner: x-coordinate for node 1 as node[1].x y-coordinate for node 2 as node[2].y, or in some way that eases referencing as a lot of computation will have to be done. I really hope to get some replies.. Thank you so much! |
|
#2
|
|||
|
|||
|
There are various answers to your question, as most development problems do...
I would suggest that you do a two pass reading. 1. First pass will only determine how many nodes are needed, since no actual parsing is done this will be extremely fast (if not reading from a floppy ).2. Then allocate the array of Nodes: Node *Nodes = new Node[number_nodes]; 3. Read the file and fill the array with nodes. You can access it with Nodes[0].x Another solution would be setting a maximum nr of nodes: Node *Nodes[MAX_NODES]; Then for every read coordinate from the file you allocate a node in memory: Node[0] = new Node; In this case it is wise to change the struct to a class object, so that you can use the constructor to set the x, y and z; Like: Node[0] = new Node(x, y, z); You access it with Node[0]->x Since the most time consuming action will be the computation, it does not really matter. This makes me wonder why not just statically allocate the max ammount of nodes. It is not really that much memory, and no fuss with allocation and deallocation and the danger of hitting unallocated memory. Besides this, the speed during calculation will not differ. The compiler and linker will optimize the memory access. |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > help needed on dynamic data allocation.. |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|