Home > Blockchain >  Access child in nested vector of unknown depth using vector of indexes
Access child in nested vector of unknown depth using vector of indexes

Time:10-22

My goal is to be able to have a vector of indexes and navigate to that in a class with a vector of variants of vectors and that class.

Say I have an "index vector" of unknown size with {0, 4, 7, 2} I would want to somehow use that to access someVector[0][4][7][2].

someVector is of a class node defined as:

class node
{
  public:
    node operator[](unsigned int index)
    {
      return std::get<node>(children[index]);
    }

  private:
    std::vector<std::variant<node, std::string>> children;
}

I had the idea of using a loop and a reference but couldn't figure that out. My idea was something along the lines of

node elementRef = &nodeObject;
for (int i = 0; i < vector.size(); i  )
{
  tempElementRef = &elementRef[indexVector[I]];
  elementRef = tempElementRef;
}

CodePudding user response:

With C 20 you can do it like this:

node accessNode(node n, std::span<unsigned int> span)
{
    return span.size() ? accessNode(n[span[0]], span.subspan(1)) : n;
}

example usage:

std::vector<unsigned int> coordinates = {0, 4, 7, 2};
accessNode(someNode, coordinates);

note: Handling exceptions from bad indices or children that are not nodes is left up to you.

  •  Tags:  
  • c
  • Related