Build a wrapper class for array like objects

The wrapper class will have a constructor that will accept any array-like data structures like vector or array and convert store it as a vector variable present in the class.

I have provided my custom collection class below

1
2
3
4
5
6
7
8
9
10
11
12
template <class T, class T1>
class collection
{
private:
    std::vector<T> list;
public:
    collection(T1 list, int size=-1)
    {
        for (int i = 0; i < size; i++)
            this->list.push_back(list[i]);
    }
};
Last edited on
I guess your question is: How such a constructor would look like?

Starting with C++11 it is rather simple:
1
2
3
4
5
6
7
8
9
10
11
12
13
template <class T, class T1>
class collection
{
private:
    std::vector<T> list;
public:
    template <class T1>
    collection(const T1& data_container)
    {
        for (auto d = std::begin(data_container); d != std::end(data_container); ++d)
            this->list.push_back(d);
    }
};
Also, I'd recommend using more descriptive type names than T and T1, e.g. ElementT and ContainerT. It makes the code clearer to anyone using it.
Last edited on
1
2
this->list.push_back(d);
list.push_back(*d);
Wouldn't it be better to use a range based for loop?
1
2
3
4
5
6
    template <class T1>
    collection(const T1& data_container)
    {
        for (auto &d : data_container)
            list.push_back(d);
    }


And don't call a vector "list".
Topic archived. No new replies allowed.