Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-dimensional vector initialization

I have following std::vector declaration:

std::vector<std::vector<std::vector<int> > > m_input;

I am initializing it as follows:

    m_input.resize (100);
    m_output.resize(100);
    for (int i = 0; i < 100; ++i) {
        m_input [i].resize(100);
        m_output[i].resize(100);
        for (int j = 0; j < 100; ++j){
            m_input [i][j].resize(100);
            m_output[i][j].resize(100);
        }
    }

How can I achieve this via the member initializer list?

like image 785
Avinash Avatar asked Jun 27 '11 10:06

Avinash


2 Answers

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)))

like image 131
MSalters Avatar answered Sep 24 '22 03:09

MSalters


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.

like image 41
sbi Avatar answered Sep 26 '22 03:09

sbi