5

I probably didn't word the question very well, but here's an example of what I mean. An unordered_map can be created like so:

unordered_map<string,int> map = {
    {"A", 3},
    {"B", 2},
    {"C", 1}
};

What I'm wondering is how can I make my own class that can function this way? Like, how are all of the values passed to the map interpreted? How can I access each individual value in the array I'm assigning to it? In fact, would it even be an array, because the values don't all necessarily share a type?

Captain_D1
  • 61
  • 4
  • 5
    https://en.cppreference.com/w/cpp/language/list_initialization `Q(std::initializer_list) {}` – Jeffrey Sep 22 '21 at 01:54
  • 5
    See [`std::initializer_list`](https://en.cppreference.com/w/cpp/utility/initializer_list) – kakkoko Sep 22 '21 at 01:55
  • Does this answer your question? [What does initializer\_list do?](https://stackoverflow.com/questions/34957393/what-does-initializer-list-do) – alter_igel Sep 22 '21 at 02:13
  • The [literals](https://en.cppreference.com/w/cpp/language/expressions#Literals) of C++ consist of integer literals, character literals, floating-point literals, string literals, boolean literals, and `nullptr`, plus user-defined literals (which look a lot like one of the other literals). So, right, your choice of terminology was a bit off. Good thing you followed up with an example. – JaMiT Sep 23 '21 at 04:37

1 Answers1

4

The class you are looking for is std::initializer_list. It is a container, like std::vector, and you can easily iterate over it in the same way. Simply define the public constructor that takes the initializer_list:

class FromList {
public:
  FromList(std::initializer_list<std::string> list) {
    for (const auto &passed_list_entry: list) {
       // We have the values here
    }
  }
};

// And using it:
FromList v = { "entry_1", "entry_2", "entry_3" };
Audrius Meškauskas
  • 20,936
  • 12
  • 75
  • 93