Implementing an array initializer

You can declare and initialize regular arrays in one line, for example:

int PowersOfTwo[] = {1, 2, 4, 8, 16, 32, 64, 128};

Is there a way to reproduce this behavior in custom classes? So for example:

MyClass<int> PowersOfTwo = {1, 2, 4, 8, 16, 32, 64, 128};

You may have a copy constructor that takes an array as its parameter, but you still have to declare the array in the previous line.

int InitializationArray[] = {1, 2, 4, 8, 16, 32, 64, 128};
MyClass<int> PowersOfTwo = InitializationArray; 
+5
source share
2 answers

You can implement your class so that you can write this:

MyClass<int> array;
array = 1,2,3,4,5,6,7,8,9,10;//dont worry - all ints goes to the array!!!

Here is my implementation:

template <class T>
class MyClass
{
   std::vector<T> items;
public:

    MyClass & operator=(const T &item)
    {
       items.clear();
       items.push_back(item);
       return *this;
    }
    MyClass & operator,(const T &item)
    {
       items.push_back(item);
       return *this;
    }
    size_t Size() const { return items.size(); }
    T & operator[](size_t i) { return items[i]; }
    const T & operator[](size_t i) const { return items[i]; }

};

int main() {

        MyClass<int> array;
        array = 1,2,3,4,5,6,7,8,9,10;
        for (size_t i = 0 ; i < array.Size() ; i++ )
           std::cout << array[i] << std::endl;
        return 0;
}

Conclusion:

1
2
3
4
5
6
7
8
9
10

Watch the online demo: http://www.ideone.com/CBPmj

You can see two similar solutions here that I posted yesterday:


EDIT:

, , STL. , :

std::vector<int> v;
v+=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15; //push_back is called for each int!

, () , :

template<typename T>
std::vector<T>& operator+=(std::vector<T> & v, const T & item)
{
    v.push_back(item); return v;
}
template<typename T>
std::vector<T>& operator,(std::vector<T> & v, const T & item) 
{
    v.push_back(item); return v;
}

: http://ideone.com/0cIUD


:

++. :

std::vector<int> v;
v << 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15; //inserts all to the vector!

, !

+6

, , ++ 0x.

, boost.assign.

+4

All Articles