如何在C ++中使用多维向量 [英] How to use Multidimensional vector in C++

查看:91
本文介绍了如何在C ++中使用多维向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在设置2d和3d向量中的值时遇到了一些问题.
我想知道创建和返回2维和3维矢量值的过程,其中大小将动态更改.

我也尝试了以下代码,但没有得到任何帮助:


3D向量:

Hi,

I got some problem to set the values in 2d and 3d vector.
I want to know the process to create and return the 2dimensional and 3dimensional vector values where size will be changed dynamically.

I also tried the following code but i didn''t get any help:


3D vector:

vector < vector < vector<int> > > tube;

for(int i=0;i<2;i++)
{
   for(j=0;j<4;j++)
   {
     for(k=0;k<15;k++)
     {
     tube.push_back( vector< vector<int> >() );
     tube[k].push_back (vector<int> ());
     tube[i][j].push_back(value)
     }
   }
}



但我不知道它是否会工作,也不知道应该在哪里设置i,j,k参数.

而且我也想对2D向量做同样的事情

请让我知道执行此操作的正确方法是什么.

谢谢...



but I don''t know whether it will work and also don''t know where should I set i,j,k parameter.

and I also want to do the same thing for 2d vector

Please let me know that what is the correct way to do this.

Thanks...

推荐答案

可能您的意思类似于
Possibly you mean something similar to
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;



int main ()
{
  vector < vector < vector<int> > > tube;
  for(int i = 0; i < 2; i++)
  {
    vector < vector < int > > w;
    tube.push_back( w );
    for(int j = 0; j < 4; j++)
    {
      vector <int> v;
      tube[i].push_back( v );
      for(int k = 0; k < 15; k++)
      {
        tube[i][j].push_back( rand());
      }
    }
  }

  for (size_t i = 0; i < tube.size(); i++)
    for (size_t j = 0; j < tube[i].size(); j++)
      for (size_t k = 0; k < tube[i][j].size(); k++)
        cout << "tube[" << i << "][" << j << "][" << k << "] = " << tube[i][j][k] << endl;   
}



?



?


vector < vector < vector<int> > > tube;
for(int i=0;i<2;i++)
{
   tube.push_back(vector<vector<int> >());
   for(int j=0;j<4;j++)
   {
       tube[i].push_back(vector<int>());
       for(int k=0;k<15;k++)
       {
           tube[i][j].push_back(value);
       }
   }
}


或更有效:


OR more efficiently:

vector < vector < vector<int> > > tube;
tube.resize(2);
for(int i=0;i<2;i++)
{
   tube[i].resize(4);
   for(int j=0;j<4;j++)
   {
       tube[i][j].resize(15, value);
   }
}


但是,如果您不得不经常使用3D向量并调整其大小,那么为该工作编写一个专门的类是有利可图的,但这比我们在这里讨论的要困难一些.


However if you have to use and resize 3D vectors often then its profitable to write a specialized class for the job but that''s a bit more difficult than what we are discussing here.


这篇关于如何在C ++中使用多维向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆