首页 > 解决方案 > 整数对向量

问题描述

我被要求获得一个值N,然后我将获得N成对的值。这些对将是我的二维数组的大小,并且这个二维数组的元素范围从 1 到二维数组的大小。

样本输入:

N = 2

两对值是

(2,3)
(3,4)

样本输出:

{(1,2,3),(4,5,6)}
{(1,2,3,4),(5,6,7,8),(9,10,11,12)}

下面的代码是我尝试过的。我还是一个初学者,所以请帮助我。

#include<bits/stdc++.h>
using namespace std;

makeArray(int a, int b){
   int arr[a][b];
   int temp = 1;
   cout<<"[";
   for(int i=1; i<=a; i++){
       cout<<"[";
       for(int j=1; j<=b; j++){
           cout<<temp<<",";
       }
       cout<<"]";
   }
   cout<<"]";
}

int main() {
   int n;
   cin>>n;
   int a,b;
   vector<pair<int,int>> ip;
   for(int i=0; i<n; i++){
       cin>>a;
       cin>>b;
       ip.push_back(make_pair(a,b));
   }
   for (int x=0; x<n; x++)
   {
       makeArray(ip.first, ip.second);
       cout<<endl;
   }
   return 0;
}

标签: c++arraysstdvector

解决方案


我不太明白任务是什么,但我修复了代码中的一些错误,以便它运行并满足您提供的示例。

#include<bits/stdc++.h>
using namespace std;

void makeArray(int a, int b){
   //int arr[a][b];
   int temp = 0;
   cout<<"[";
   for(int i=1; i<=a; i++){
       cout<<"[";
       if (1 <= b)
           cout << ++temp;
       for(int j=2; j<=b; j++){
           cout << "," << ++temp;
       }
       cout<<"]";
   }
   cout<<"]";
}

int main() {
   int n;
   cin>>n;
   int a,b;
   vector<pair<int,int>> ip;
   for(int i=0; i<n; i++){
       cin>>a;
       cin>>b;
       ip.push_back(make_pair(a,b));
   }
   for (int x=0; x<n; x++)
   {
       makeArray(ip[x].first, ip[x].second);
       cout<<endl;
   }
   return 0;
}

更具体地说,在main()函数中,第二个 for 循环:

   for (int x=0; x<n; x++)
   {
       //makeArray(ip.first, ip.second);
       makeArray(ip[x].first, ip[x].second);
       cout<<endl;
   }

您忘记使用方括号运算符[]来访问向量的元素。

makeArray函数中:

  1. arr不使用变量。

  2. 忘记返回类型 ( void)。

  3. 您不增加temp变量,因此最终打印 1 而不是范围1形式a * b

  4. 打印最后一个整数后有一个尾随逗号

使固定:

// return type is required
void makeArray(int a, int b){ 
   //int arr[a][b]; variable not used.
   //temp is later incremented, so the first
   //element printed will be 1.
   int temp = 0;
   
   cout<<"[";
   for(int i=1; i<=a; i++){
       cout<<"[";
       //We do not know, if we only need 1
       //integer printed, so to not have a trailing
       //comma at the end, we print the first integer
       //outside the array
       if (1 <= b)
               cout << ++temp;
       //because the first integer is already printed,
       //we start from the second
       for(int j=2/*1*/; j<=b; j++){
           //cout<<temp<<",";
           cout << "," << ++temp;
       }   
       cout<<"]";
   }   
   cout<<"]";
}

输入:

2
2 3 3 4

输出:

[[1,2,3][4,5,6]]
[[1,2,3,4][5,6,7,8][9,10,11,12]]

推荐阅读