C++ Flexible Nested Array / Vector Structure

I’m trying to convert an object from P5.js (Javascript) to OpenFrameworks (C++).

The object I made in Javascript contains a combination of strings, a single array of strings or nested arrays of strings (etc), see below:

let array = {
    "string1",
    ["string2","string3"],
    ["string4",["string5","string6"]]
}

I’ve tried making it in C++ using vectors but I keep running into the problem of not having the flexibility for it to hold strings, arrays or arrays within arrays (as my p5.js code can currently parse through unpack these strings as needed).

Thank you for your help in advance! :slight_smile:

Hi @xX_n3c40_Xx ,
just make a custom structure like this:


struct customElement{
std::string s;
int a;
float b;
};

struct CustomArrayStruct {

std::vector < int > vecInt;
std::vector < std::string > vecString;
std::vector < std::vector < std::string > > vecVecString
std::vector < customElement> vecCustom;
//etc...
};

Hope this helps,

Best,

P

Hi @xX_n3c40_Xx ,

Compared to javascript C++ is a statically typed language which make this kind of operations possibly non trivial. There is multiple ways to solve this though, one of them is infering the underlying structure (here a tree of strings, or so it seems) to construct it.

For example :

#include <vector>
#include <string>

struct StrNode {  
  StrNode(std::string const& _s) : s(_s) {}
  StrNode(std::initializer_list<StrNode> const& _children) : children(_children) {}

  std::string s;
  std::vector<StrNode> children;
};

using StrTree = std::vector<StrNode>;

int main() {
  StrTree tree{
    StrNode( "string1" ),
    StrNode({ "string2", "string3" }),
    StrNode({ StrNode("string4"), StrNode({ "string5", "string6" }) }),
  };
}

This could probably be improve or adapted to fit your need.

Also, if your structure is not deeper than that, you can do this :

#include <vector>
#include <string>

struct StrNode {  
  std::string s;
  std::vector<std::string> children;
};

using StrTree = std::vector<StrNode>;

int main() {
  StrTree tree{
    { "string1", {} },
    { "", { "string2", "string3" } },
    { "string4", { "string5", "string6" } },
  };
}

or this :

using StrNode = std::vector<std::string>;
using StrTree = std::vector<StrNode>;

int main() {
  StrTree tree{
    { {"string1"} },
    { { "string2", "string3" } },
    { "string4", { "string5", "string6" } },
  };
}

I would recommend using Json. The included json library is super powerful. https://github.com/nlohmann/json/
I am not sure though about the overhead you will get from using it versus using standard containers (std::vector, std::map, etc)