Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to make a nested list in C++?

For those who know Python, the best way to explain what I want is by analogy:

[1, [2, 3], 4, [5, [6]], 7]

Obviously, I can implement my own class (template) to do this, but if the standard library has already invented this wheel, I want to avoid re-inventing it (or at least, avoid putting my half-baked re-invented version in my project).

like image 667
allyourcode Avatar asked Jan 25 '23 07:01

allyourcode


1 Answers

Under the hood, a python list is a dynamically reallocating array, i.e. the same sort of thing as a std::vector, and its elements are dynamic, i.e. the same sort of thing as std::any. So the most direct analogue of this code would be

using p = std::vector<std::any>;

auto myList = p { 1, p { 2, 3 }, 4, p { 5, p { 6 } }, 7};
like image 57
Daniel McLaury Avatar answered Jan 26 '23 20:01

Daniel McLaury