0

I have a constructor as such:

class MyClass {
  protected:
    std::size_t size1;
    std::size_t size2;
    std::array<std::array<std::pair<std::uint64_t, std::uint64_t>>> items;
  public:
    MyClass(): MyClass(1, 1, <???>) {}
    MyClass(std::size_t size1, std::size_t size2): size1(size1), size2(size2), <???> {}
};

I'm not sure if the above part can be done: to initialize the array of arrays of pairs to all 0 based on the sizes provided by size1 and size2. I've Googled around a bit but can't seem to run into code examples of this. Any help would be appreciated.

2
  • 8
    You cannot. std::array size is fixed and must be known at compile time. You might want to use std::vector instead. Commented Oct 7, 2021 at 17:48
  • If you have sufficient storage available and you know the maximum possible size of the array, you can allocate for the maximum size and use only the portion of the the array required by the user. This is sometimes preferable to using std::vector, but usually only when the maximum possible size is fairly small. Commented Oct 7, 2021 at 17:59

1 Answer 1

3

As Yksisarvinen mentioned, std::array needs to know its size at compile time. If you need to set the size at runtime, then use std::vector instead. However, if you do know the size at compile time, then make MyClass a template and pass the desired sizes as template parameters:

template<std::size_t size1 = 1, std::size_t size2 = 1> {
protected:
    std::array<std::array<..., size2>, size1> items{};
public:
    MyClass() = default;
    ...
};

Note that the {} after the declaration of items ensures all the values are set to zero. And then you can instantiate it like so:

MyClass<3, 5> myObject;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.