Home > Software engineering >  How to implement operator[][] for 1D arrays
How to implement operator[][] for 1D arrays

Time:02-20

Is there a way to implement an operator like [][] for a 1D array?

I want to change the implementation of a 2D vector to a 1D vector in my code (cause this increases the execution speed by about P in my program). 2D vector supports [y][x]. How can I have such functionality for a 1D vector?

I can do it like this:

const size_t Y_Axis { 20 };
const size_t X_Axis { 30 };

std::vector<char> vec( Y_Axis * X_Axis );

size_t row { 5 };
size_t col { 28 };
vec[ row * X_Axis   col ] = 't'; // assign a value to a specific row-column

However, typing this formula multiple times throughout a source file seems like violating DRY (don't repeat yourself). How can I do this in an efficient and idiomatic way? I want to hide the complexity and make things a bit abstracted just like operator[][] of 2D vector does.

CodePudding user response:

C does not allow virtual containers. So the operator [] is expected to return a true object of the expected size, if you want all the goodies like true iterators to work smoothly.

Here is a post of mine about the iterator question for multi-dimensional containers and a more general question on Code Review

If you only want to build an operator[](int) that returns something that can accept a second [], it can easily be done for a 2D vector, by returning a plain pointer inside the internal data array of a vector:

template <typename T>
class vec2d {
    std::vector<T> data;
    size_t _cols;

public:
    vec2d(int rows, int cols, T* src = nullptr)
        : data(rows * cols), _cols(cols) {
        if (src != nullptr) {
            for (T& val : data) {
                val = *src  ;
            }
        }
    }

    T* operator [] (size_t row) {
        return data.data()   row * _cols;
    }

    const T* operator [] (size_t row) const {
        return data.data()   row * _cols;
    }

    size_t rows() const {
        return data.size() / _cols;
    }

    size_t cols() const {
        return _cols;
    }
};

And here is an example usage:

int main() {
    vec2d<char> v(3, 4, "ABCDEFGHIJKL");

    for (size_t i = 0; i < v.rows(); i  ) {
        for (size_t j = 0; j < v.cols(); j  ) {
            std::cout << v[i][j] << ' ';
        }
        std::cout << "\n";
    }
}
  • Related