I have a piece of code that I'm migrating from Fortran to C++, and I'd like to avoid some of the nested for loop structures I had to create in the original F77 code.
The problem is this: I have a vector of objects called nodes that each include a vector holding (among other important info) the indices of other node objects to which each is connected (a connection graph). Like this
struct Node {
vector<int> conNode;
};
vector<Node> listOfNodes;
vector<int> nodeListA; // a subset of nodes of interest stored as their vector indices
I need to look for nodes that nodes in nodeListA are connected to, but only if those nodes are also in nodeListA. Right now, my code looks something like this:
// Loop over the subset of node indices
for (int i=0; i<nodeListA.size(); i++) {
// Loop over the nodes connected to the node i
for (int j=0; j<listOfNodes[nodeListA[i]].conNode.size(); j++) {
// Loop over the subset of node indices again
for (int k=0; k<nodeListA.size(); k++) {
// and determine if any of node i's connections are in the subset list
if (nodeListA[k] == listOfNodes[nodeListA[i]].conNode[j]) {
// do stuff here
}
}
}
}
There HAS to be a much simpler way to do this. It seems like I'm making this way too complicated. How can I simplify this code, possibly using the standard algorithm library?