*编辑:仍然,当第1行输入3列,第2行输入2列时,输出中的第1行将变为2元素作为第一行。
输出具有单独动态分配的列数的动态分配的equip数的问题(对于每个设备的捕获数)...也就是说,如果我尝试分配2个equipes,然后第一个配备两个“渔获物”(两列),第二个配备三个渔获物,一切都是可以的……但是,如果我尝试输入第二行(设备)的较小数量的列(“捕获”),那么在输出中第一行的“多余”被“切断”,所以例如,如果有3列输入第一行和2列输入第二行,在输出中将只有两列(数字索引)的每两行。
#include<iostream>
int main()
{
using namespace std;
int *sum;
int *a = new int;
int *b = new int;
cout << "Total number of equips: ";
cin >> *a;
// Allocate a two-dimensional 3x2 array of ints
int** ippArray = new int*[*a];
for (int i = 0; i < *a+1; ++i) {
ippArray[i] = new int[*b];
}
// fill the array
for (int i = 1; i < *a+1; ++i) {
cout << "Total number of catches for " << i << "th equip : ";
cin >> *b;
cout << "Equip number: " << i << endl;
for (int j = 1; j < *b+1; ++j) {
cout << "Catch number: " << j << endl;
cin >> ippArray[i][j];
ippArray[i][j];
}
}
// Output the array
for (int i = 1; i < *a+1; ++i) {
for (int j = 1; j < *b+1; ++j) {
cout << ippArray[i][j] << " ";
*sum = *sum + ippArray[i][j];
}
cout << endl;
}
cout << endl;
cout << "All catches of the all equipes: " << *sum-3;
// Deallocate
for (int i = 1; i < *a+1; ++i) {
delete [] ippArray[i];
}
delete [] ippArray;
// Keep the window open
cin.get();
return 0;
}发布于 2015-08-25 01:42:19
首先,除非确实需要,否则不要将整数转换为指针(int *a = new int;)。这使得代码更难阅读,如果有人不得不维护你的代码,他们会叫你a-hole。
第二,int** ippArray = new int*[*a];结合了多个点,你可以这样做...for (int i = 1; i < *a+1; ++i)很糟糕。ippArray具有从0到*a的有效引用,因此它应为for (int i = 0; i < *a; ++i)
编辑:尝试像这样的http://ideone.com/4egQl3
Edit2:还有一个标准的建议...
{
std::vector<string> advice;
advice.push_back( "These will make your life easier" );
}
// No de-allocation needed!发布于 2017-03-17 19:39:48
程序的某些部分具有未定义的行为
清理干净后,你的代码就变成了
int main()
{
using namespace std;
int sum, a, b;
cout << "Total number of equips: ";
cin >> a;
typedef vector<vector<int> > vvint;
typedef vector<int> vint;
// Allocate a two-dimensional structure of ints
vvint ippArray(a);
// fill the array
for (vvint::size_t i = 0; i < a; ++i) {
cout << "Total number of catches for " << i+1 << "th equip : ";
cin >> b;
cout << "Equip number: " << i+1 << endl;
ippArray[i] = vint(b);
for (int j = 0; j < b; ++j) {
cout << "Catch number: " << j+1 << endl;
cin >> ippArray[i][j];
}
}
// Output the array
for (const vint & inner : ippArray) {
for (int num : inner) {
cout << num << " ";
sum += num;
}
cout << endl;
}
cout << endl;
cout << "All catches of the all equipes: " << sum;
cin.get();
return 0;
}https://stackoverflow.com/questions/32188309
复制相似问题