C++ 多维向量初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6491251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:14:52  来源:igfitidea点击:

Multi-dimensional vector initialization

c++stlvectorinitialization

提问by Avinash

I have following std::vectordeclaration:

我有以下std::vector声明:

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

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?

如何通过成员初始值设定项列表实现此目的?

回答by MSalters

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_inputwith 100 copies of a std::vector<std::vector<int> >, so it'd be : m_input(100, X). Now, that Xin turn is a vector of 100 std::vector<int>, which in turn contains a hundred ints:

std::vector<T>有一个构造函数,它接受两个参数,一个元素数量和一个初始值。在您的情况下,您希望m_input使用 100 个副本进行初始化std::vector<std::vector<int> >,因此它是: m_input(100, X). 现在,这X又是一个 100 的向量,std::vector<int>它又包含一百个整数:

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

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

回答by sbi

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.

也就是说,正如 Viktor 在对该问题的评论中所说的那样,应该通过投影到一维领域来实现多维领域。

回答by deceleratedcaviar

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

如果您可以断言您的向量维度将具有固定长度,那么为什么不使用std::array

For example:

例如:

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

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_Sehrin the comments), without the added implementation woes of accessing a 1-dimensional array in a 3-dimensional way.

这样您就可以利用所有连续分配的内存(如Viktor_Sehr在评论中暗示的 那样),而不会增加以 3 维方式访问 1 维数组的实现问题。