Nick Chapman
Nick Chapman

Reputation: 4634

Implementing a Python-like List in C++

The answer to this almost certainly exists elsewhere I just can't come up with the words for this, please feel free to direct me to other resources.

I am looking to implement a Python-esque list in C++. I do not mean I want to create a vector. I know how that is done. What I am looking to do is create a data structure that could store values such as:

[1, "a", 3.5]

like in Python. I also want it to be dynamic in size.

Is there a name for this? Is this already implemented somewhere?

I have been experimenting with a linked list that contains templated nodes, but I don't know how to write the accessing function which will get node i when node i will have potentially any data type. Thoughts, suggestions? Thank you in advance.

Upvotes: 0

Views: 499

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

like in Python. I also want it to be dynamic in size.

Well, for fixed sizes a std::tuple<> should serve you well.

Is there a name for this? Is this already implemented somewhere?

The "name for this" is, a container serving to store an arbitrary sequence of types with dynamic size. Though the focus is on the arbitrary type placeholder.

Unfortunately there's no std::any type in the current standard, that supports dynamically sized containers like std::vector<std::any>.

If you don't have access to an experimental implementation with your toolchain, you might be able to use the boost::any type.

Upvotes: 1

Edward Strange
Edward Strange

Reputation: 40877

You want a vector of any. The any type comes in boost or C++17.

Upvotes: 0

Related Questions