C++第10课 STL容器 (十一)

1.initalizer_list(列表)

template <class _Ty>
class MyVector 
{
public:
    MyVector(int size) :curSize(0) 
    {
        dataMemory = new _Ty[size];
    }
    MyVector(initializer_list<_Ty> data) :MyVector(data.size()) 
    {
        for (auto v : data) 
        {
            dataMemory[curSize++] = v;
        }
    }
    void print() 
    {
        for (int i = 0; i < curSize; i++) 
        {
            cout << dataMemory[i] << "\t";
        }
        cout << endl;
    }

protected:
    _Ty* dataMemory;
    int curSize;
};
void testCreateListData()
{
    initializer_list<int> data1 = { 1,2,3 };
    initializer_list<int> data2 = { 1,2,3,4 };
    cout << data2.size() << endl;
}
template <class _Ty>
_Ty printSum(const initializer_list<_Ty>& data) 
{
    _Ty sum = 0;
    sum = accumulate(data.begin(), data.end(), sum);
    return sum;
}

int main()
{
    //{ 1,2,3,4 }    列表数据
    vector<int> data1 = { 1,2,3,4 };
    vector<int> data2 = { 1,2 };
    MyVector<int> myData = { 1,2,3 };
    MyVector<int> myData2 = { 1,2,3,4,5,6,7 };
    MyVector<int> myData3 = { 1,2,3,1,2,3,4,5,6,7 };
    myData3.print();
    cout << printSum({ 1,2 }) << endl;
    cout << printSum({ 1,2,3 }) << endl;
    cout << printSum({ 1,2,3,4}) << endl;
    return 0;
}

 

C++第10课 STL容器 (十一)

上一篇:docker-compose kafka集群部署,kafka-manager可视化访问页面增加用户密码校验


下一篇:【ybtoj】【倍增问题】删边问题