… and thanks for reading…
I’m still learning the ropes so please be forgiving… 😉
I am writing a function that meshes a solid in space. The mesh is done by using objects of a ‘Node’ class and each node is represented by:
int id double p double r
Initially I thought that a map would be the way to go: with a map I can make the association between the ‘id’ key and the second key (a pointer to the node object).
Something like this:
int nodeId; Node *node; std::map<int, Node *> NodeMap;
Then, when I create the nodes I just call the ‘new’ operator. E.g in a for loop I do something like this:
node = new Node(i); // the node constructor sets the id to the value of i.
and I add the new node to the map:
NodeMap[i] = node;
But…. I realized that I will need to do a lookup in the map not by first key (the id) but by the p and r parameters (the coordinates of the node).
In other words I will need something that returns the node id given the values of p and r. A map is a perfect container if the lookup is done using the integer first key (id). Does anyone have a suggestion on how to solve this particular problem?
Thanks much! AsvP.
A map<> won’t work. C++ associative containers work on the basis of key equality, and comparing floating-point numbers for equality doesn’t work at all well.
It sounds like you need to find a node, given x and y. The best way will depend on what you’re trying to accomplish. Are you trying to find the nearest node, given the coordinates, or are you going to calculate coordinates that are very close to a node, and then you need to find the node?
For the second, you’ll probably be well off sorting the nodes on either the x or y coordinate (I’ll assume the x), and doing a binary search to find which nodes have x coordinates very close to your given x. That will generally select a small number of nodes, which can be searched for the approximately correct y.
(Of course, if the nodes are in some sort of predictable grid, you should be able to provide some means to calculate directly, like round x and y to nearest integer if you’ve got integral lattice points.)
If you need to find the closest node, well, that gets a bit complicated. I don’t know enough about this to help much, but there are resources for geometric algorithms.