Multi-dimensional vector initialization

后端 未结 3 1461
南笙
南笙 2020-12-28 22:28

I have following std::vector declaration:

std::vector > > m_input;

I am initializing

相关标签:
3条回答
  • 2020-12-28 22:41

    std::vector<T> has a constructor that takes two arguments, a number of elements and an initial value. In your case, you want to initialize m_input with 100 copies of a std::vector<std::vector<int> > , so it'd be : m_input(100, X). Now, that X in turn is a vector of 100 std::vector<int>, which in turn contains a hundred ints:

    : m_input(100, std::vector<std::vector<int> >(100, std::vector<int>(100, 0)))

    0 讨论(0)
  • 2020-12-28 22:47
    my_class::my_class()
     : m_input(100, std::vector< std::vector<int> >(100, std::vector<int>(100) ))
    {
    }
    

    That said, implementing a multi-dimensional field should be done by projecting into a one-dimensional one, as Viktor said in his comment to the question.

    0 讨论(0)
  • 2020-12-28 23:04

    If you can assert that your vector dimensions are going to be of a fixed length, then why not use std::array?

    For example:

    std:array<std::array<std::array<int, 100>, 100>, 100>

    That way you can take advantage of all the memory being contiguously allocated (as hinted at by Viktor_Sehr in the comments), without the added implementation woes of accessing a 1-dimensional array in a 3-dimensional way.

    0 讨论(0)
提交回复
热议问题