Created
July 21, 2021 04:54
-
-
Save allyourcode/fb770d37f8613863e0023d901cbd63c8 to your computer and use it in GitHub Desktop.
In Python, we can do nested lists right out of the box. E.g. [1, [2, 3], 4, [5, [6]], 7]. In C++, we must jump through some hoops, but it can be done.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <initializer_list> | |
#include <vector> | |
using namespace ::std; | |
template <typename E> | |
class NestedList { | |
public: | |
class Element { | |
public: | |
Element(const E& e) | |
: holding_primitive_type_(true), element_(e) {} | |
Element(initializer_list<Element>&& children) | |
: holding_primitive_type_(false), children_(children) {} | |
friend ostream& operator<< (ostream& out, const Element& e) { | |
if (e.holding_primitive_type_) { | |
out << e.element_; | |
return out; | |
} | |
NestedList::Print(&out, e.children_); | |
return out; | |
} | |
private: | |
// Determines which of the next two variables holds our contents | |
bool holding_primitive_type_; | |
E element_; | |
vector<Element> children_; | |
}; | |
friend class Element; | |
NestedList() = default; | |
NestedList(initializer_list<Element>&& initial_contents) | |
: contents_(initial_contents) {} | |
void push_back(const E& e); | |
vector<Element>& push_back_empty(); | |
friend ostream& operator<< (ostream& out, const NestedList& lst) { | |
Print(&out, lst.contents_); | |
return out; | |
} | |
static void Print(ostream* os, const vector<Element>& lst) { | |
auto& out = *os; | |
out << "{"; | |
bool first = true; | |
for (const auto& child : lst) { | |
// Separating comma. | |
if (first) { | |
first = false; | |
} else { | |
out << ", "; | |
} | |
out << child; | |
} | |
out << "}"; | |
} | |
private: | |
vector<Element> contents_; | |
}; | |
int main(int argc, char* argv[]) { | |
NestedList<int> lst = {1, {2, 3}, 4, {5, {6}}, 7}; | |
cout << "NestedList: " << lst << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think variant could help us clean this up...