c++ - 有指针的计算机实验室

标签 c++ pointers

我的任务是管理计算机实验室。具体来说,有 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并获取对其元素的引用(在本例中是对 vectorStation 的引用。这与以下内容相同:

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/

相关文章:

c# - 为什么 DwmGetWindowAttribute 与 DWMWA_EXTENDED_FRAME_BOUNDS 在切换监视器时表现异常?

C++:在成员函数中通过引用返回成员变量

c - 迭代存储在堆上的数组

c++ - 如何将值插入到特定索引处的 C++ boost::multiindex 集合中,如 std::list

c++ - 链接 operator= 用于只写对象 - 可以返回 rhs 而不是 *this?

c - 警告 : comparison between pointer and integer in C

c - 我在指针和动态数组方面遇到了困难

c++ - 检查值的范围是升序、降序还是非单调

c++ - std::regex 构造函数抛出异常

C++11 原子库 std::compare_and_exchange 语义