c++ - 整数对向量
问题描述
我被要求获得一个值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;
}
解决方案
我不太明白任务是什么,但我修复了代码中的一些错误,以便它运行并满足您提供的示例。
#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
函数中:
arr
不使用变量。忘记返回类型 (
void
)。您不增加
temp
变量,因此最终打印 1 而不是范围1
形式a * b
打印最后一个整数后有一个尾随逗号
使固定:
// 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]]
推荐阅读
- html - 将文本对齐到按钮单选的右侧
- c# - 控制所有呈现的模式 iOS
- python - 魔术 8 球程序循环未按预期工作
- r - 在 R 中循环查找上一个匹配项
- r - R Highcharter Drilldown Set Ymin & Ymax + Title for each layer
- twitter-bootstrap - Bootstrap 3 到 4 迁移(模式停止出现)
- android - Firebase 返回 null 但数据存在
- c# - Xamarin 形式 - MVVM 可观察集合始终为空
- python - 对列表中的元组求和
- django - 将日期范围与 FilterSet Django 一起使用