Home > OS >  Initialize custom collection with list of values
Initialize custom collection with list of values

Time:11-18

I have created a class that should act as a collection (with some custom behavior of mine). Inside, the class contains an array, to store the values.

class MyCollection {

private:         
    int m_array[N];

public:

    int operator [] (int idx) const {
        return m_array[idx];
    }
    
    int operator [] (TKey k) {
        return m_array[idx];
    }
};

I would like to be able to initialize an instance of this class like it can be done with arrays, but I don't know how to do it, or what this kind of initialization is called ot then look on the web.

std::array<int, 3> a2 = {1, 2, 3};

How can this be achieved? Please note that I may change the type of the elements of the collection (even template it), the referred int is just an example.

CodePudding user response:

The std::initializer_list will be your friend.

We can add it in a constructor, but also in an assignment operator, or any other member function.

Please read about it here.

Code could look like:

#include <iostream>
#include <initializer_list>

class MyCollection {
private:
    int m_array[10]{};
public:
    MyCollection(const std::initializer_list<int> il) {
        if (il.size() <= 10) {
            size_t i{};
            for (const int& t : il) m_array[i  ] = t;
        }
    }
    int operator [] (size_t idx) const {
        return m_array[idx];
    }
};
int main() {
    MyCollection mc {1,2,3,4,5,6,7,8,9,10};

    for (size_t i{}; i < 10;   i)
        std::cout << mc[i] << '\n';
}

  • Related