我的任务是管理计算机实验室。具体来说,有 4 个实验室,每个实验室有不同数量的计算机。因此,我想创建一个带指针的二维数组,但在尝试了不同的东西之后,我指望你解决这个错误(拜托!!!)。以下是我的程序的一部分,直到出现烦人的错误为止。
我在运行 1 次后遇到运行时错误(在抛出 std::bad_array_new_length what(): std::bad_array_new_length
的实例后调用终止)当我用注释//离开该行时问题就在这里。
在lab room前面加一个&,编译器报错:lvalue required as left operand of assignment。
C++ 新手,第一次接触指针,如有任何帮助,我将不胜感激。
#include <iostream>
using namespace std;
//Global variables
const int SIZE = 4;
typedef int* Stations;
Stations *labroom;
//Function declaration:
void numberOfComputers();//Receive number of computers in each lab
int menu();//Display menu options for users
void menu_processor(int option);//process user's option
int main()
{
numberOfComputers();
menu();
menu_processor(menu());
return 0;
}
void numberOfComputers ()
{ char ans;
for (int i=0;i<SIZE;i++)
{
cout<<"Enter the number of computer stations in lab "<<i+1<<": ";
do
{
cin.get(ans);
} while (ans!='\n');
labroom [i] = new int [ans-'0'];//PROBLEM HERE
cout<<"\n";
}
}
最佳答案
那不是 C++ 代码,它只是(丑陋的)C。
在 C++ 中我们有 array
对于静态数组和 vector
对于动态数组。
首先,巧妙地选择变量或函数的名称:prefer getNumberOfComputersFromUser
而不是 numberOfComputers
.什么numberOfComputers
方法?函数名称必须描述它正在做什么。
这里是一个简化的片段:
#include <vector>
#include <array>
#include <iostream>
using namespace std;
using Station = int;
using LabRooms = array<vector<Station>, 4>;
LabRooms getNumberOfComputersFromUser()
{
LabRooms labRooms;
int roomIndex = 0;
for(auto& computersInLab : labRooms)
{
cout << "Enter the number of computer stations in lab " << ++roomIndex << ": ";
auto computerCount = 0;
cin >> computerCount;
computersInLab.resize(computerCount);
}
return labRooms;
}
解释
array
需要两个模板参数:类型和大小。元素是静态分配的,不需要新的,因为我们已经知道我们有多少个房间。不知道每个房间的电脑列表,所以我们使用 vector
可以动态增加或减少。
using LabRooms = array<vector<Station>, 4>;
与typedef array<vector<Station>, 4> LabRooms
相同但我认为更清楚
for( auto& computersInLab : labRooms)
遍历 labRooms
并获取对其元素的引用(在本例中是对 vector
的 Station
的引用。这与以下内容相同:
for(int i = 0; i < labRooms.size(); ++i)
{
auto& computersInLab = labRooms[i];
...
}
computersInLab.resize(computerCount);
使用用户指定的值调整计算机列表的大小。
现在,labRooms
是一个有4个元素的数组,每个元素都是Station
的列表.
关于c++ - 有指针的计算机实验室,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45587039/