【问题标题】:Two Hard-coded Arrays OF DIFFERENT SIZES into One 2-Dimensional Vector两个不同大小的硬编码数组到一个二维向量中
【发布时间】:2012-03-20 04:22:53
【问题描述】:

我意识到如果我想将“valArray”填充到“COLUMN 0,0”的右侧,我应该放置“[j][1]”,但是,当我这样做时,我一直收到错误。
输出: - - - - - - - - - - - - - - - - - - - - - - - - -------------------------------------------------- -------------------------------------------------- 55 0 0 0 0 0 0 0 0 0 0 0 0 --------这是第 1 行-------------------------- -------------------------------------------------- -------------------- 1 2 3 4 5 6 7 8 9 10 10 10 11 ----这是第 2 行----------------------------- -------------------------------------------------- ---------------- 77 0 0 0 0 0 0 0 0 0 0 0 0 --------这是第 3 行-------------------------- -------------------------------------------------- -------------------- 88 0 0 0 0 0 0 0 0 0 0 0 0 --------这是第 4 行-------------------------- -------------------------------------------------- ------------- 请告知如何正确填充,谢谢。

#include <iostream> 
#include <vector>
#include <Windows.h>
#include <algorithm>

using namespace std;

int main()          
{   

 int typeArray[4] = {55,66,77,88};
 int valArray[13] = {1,2,3,4,5,6,7,8,9,10,10,10,11};

 // for vector: 4 = LENGTH or NUMBER of ROWS; 13 = WIDTH or NUMBER of COLUMNS;
 //  0 = VALUE all cells are initialized to
  vector< vector <int> > myVector(4, vector<int> (13,0));

 for (int i = 0; i < 4; i++)
    {         
     myVector[i][0] = typeArray[i];

     for (int j = 0; j < 13; j++)
      {
         myVector[1][J] = valArray[j];

         }
     }      

   // print vector to screen with 2 ROWS, 3 COLUMNS
    for (int i = 0; i < 4; i++)
      {         
        for (int j = 0; j < 13; j++)
         { 
          cout << myVector[i][j] << ' ';
          }         
          cout << '\n';
      } 

    system("Pause");
    return 0; 
 }

【问题讨论】:

    标签: c++ arrays vector


    【解决方案1】:

    一个问题是循环应该是直到sizeof(typeArray)/sizeof(typeArray[0]) 而不是sizeof(typeArray)。 Sizeof 只是为您提供数组的大小(以字节为单位)。您需要将其除以每个元素的大小以获得元素的数量。

    至于如何组合数组,我认为您对 for 循环的想法是正确的,只需手动分配值即可。

    示例伪代码:

    for each element in typeArray
    myVector[i][0] = typeArray[i];
    myVector[i][1] = valArray[i];
    

    【讨论】:

    • Ethan,感谢您提供更多信息。我明天要早起,所以我明天要看看这个。我会全力以赴,然后和你一起回来,CU。
    【解决方案2】:

    您的代码不起作用的原因是您没有为 myVector 分配任何值。

    假设 typeArray 和 valArray 的长度相同,并且您想将它们放在一列中,请尝试这样的操作

    for (int j = 0; j < sizeof(typeArray)/sizeof(int); j++)
    {
         myVector[j][0] = typeArray[j];
         myVector[j][1] = valArray[j];
    }
    

    【讨论】:

    • myVector 的索引顺序错误。应该是 [j][0] 或 [j][1]。内部向量是大小为 2 的向量。
    • @EthanSteinberg 谢谢没注意到
    • Ethan,感谢您的快速响应!我明天要早起,所以我明天要看看这个。我很高兴能得到这方面的帮助。我会在星期二和你一起回来,再次发送!
    • 嗨,Ethan,我还是这个论坛的新手,只能通过编辑将修改后的代码发布到我的原始部分。有没有更好的办法?无论如何,如果你有空,请你看看我的新问题的代码。我不知道为什么这些问题的字体这么大,但是,这是内容,对吧?德克萨斯州!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 2021-12-21
    • 2012-11-13
    • 1970-01-01
    相关资源
    最近更新 更多