Operator[][] overload

前端 未结 18 2110
轮回少年
轮回少年 2020-11-22 05:46

Is it possible to overload [] operator twice? To allow, something like this: function[3][3](like in a two dimensional array).

If it is pos

18条回答
  •  眼角桃花
    2020-11-22 06:39

    With a std::vector>, you can build the inside vector using custom input operator that iterate over your data and return a pointer to each data.

    For example:

    size_t w, h;
    int* myData = retrieveData(&w, &h);
    
    std::vector > data;
    data.reserve(w);
    
    template
    struct myIterator : public std::iterator
    {
        myIterator(T* data) :
          _data(data)
        {}
        T* _data;
    
        bool operator==(const myIterator& rhs){return rhs.data == data;}
        bool operator!=(const myIterator& rhs){return rhs.data != data;}
        T* operator*(){return data;}
        T* operator->(){return data;}
    
        myIterator& operator++(){data = &data[1]; return *this; }
    };
    
    for (size_t i = 0; i < w; ++i)
    {
        data.push_back(std::vector(myIterator(&myData[i * h]),
            myIterator(&myData[(i + 1) * h])));
    }
    

    Live example

    This solution has the advantage of providing you with a real STL container, so you can use special for loops, STL algorithms, and so on.

    for (size_t i = 0; i < w; ++i)
      for (size_t j = 0; j < h; ++j)
        std::cout << *data[i][j] << std::endl;
    

    However, it does create vectors of pointers, so if you're using small datastructures such as this one you can directly copy the content inside the array.

提交回复
热议问题