【问题标题】:C++ vector<vector<int> > reserve size at beginningC++ vector<vector<int> > 开始时保留大小
【发布时间】:2015-01-22 09:28:55
【问题描述】:

在 C++ 中我有

vector<vector<int> > table;

如何调整向量的大小,使其具有 3 行和 4 列,全为零?

类似的东西:

0000 0000 0000

以便我以后可以更改

table[1][2] = 50;

我知道我可以使用 for 循环来做到这一点,但还有其他方法吗?

在一维向量中我可以:

vector<int> myvector(5);

然后我可以输入例如:

myvector[3]=50;

那么,我的问题是如何用二维甚至多维向量来做到这一点?

谢谢!

【问题讨论】:

  • 我试图回答这个问题(显然其他人也有),但它真的不清楚。保留或调整大小? “怎么做”做什么可以看到您在询问如何在构造嵌套向量时传递初始大小,但为了使其成为 SO Q&A 存储库的重要组成部分,应该对其进行整理。跨度>

标签: c++ arrays vector


【解决方案1】:
vector<vector<int> > table(3, vector<int>(4,0));

这将创建一个 3 行 4 列的向量,所有这些都已初始化 到 0

【讨论】:

    【解决方案2】:

    您可以将显式默认值传递给构造函数:

    vector<string> example(100, "example");  
    vector<vector<int>> table (3, vector<int>(4));
    vector<vector<vector<int>>> notveryreadable (3, vector<vector<int>>(4, vector<int> (5, 999)));
    

    如果是“分段”构建的,则最后一个更具可读性:

    vector<int> dimension1(5, 999);
    vector<vector<int>> dimension2(4, dimension1);
    vector<vector<vector<int>>> dimension3(3, dimension2);
    

    特别是如果您使用显式 std:: - 代码看起来像

    std::vector<std::vector<std::vector<std::string>>> lol(3, std::vector<std::vector<std::string>>(4, std::vector<std::string> (5, "lol")));
    

    应该留给不好的笑话。

    【讨论】:

      【解决方案3】:

      您可以使用来自 std::vector 的 resize()

       table.resize(4);                           // resize the columns
       for (auto &row : table) { row.resize(3); } // resize the rows
      

      也可以直接初始化为:

      std::vector<std::vector<int>> table(4,std::vector<int>(3));
      

      【讨论】:

        【解决方案4】:

        不要!您将拥有复杂的代码和垃圾内存位置。

        取而代之的是一个由 12 个整数组成的向量,由一个将 2D 索引转换为 1D 索引的类包装。

        template<typename T>
        struct matrix
        {
           matrix(unsigned m, unsigned n)
             : m(m)
             , n(n)
             , vs(m*n)
           {}
        
           T& operator()(unsigned i, unsigned j)
           {
              return vs[i + m * j];
           }
        
        private:
           unsigned m;
           unsigned n;
           std::vector<T> vs;
        };
        
        int main()
        {
           matrix<int> m(3, 4);   // <-- there's your initialisation
           m(1, 1) = 3;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-20
          • 1970-01-01
          • 2022-08-07
          • 1970-01-01
          • 1970-01-01
          • 2013-03-15
          相关资源
          最近更新 更多