c++ - 如何在动态数组中访问和使用动态数组

标签 c++ arrays pointers struct dynamic-arrays

我正尝试在我的 C++ 项目中使用一个结构,但我遇到了一些问题。在我的项目中,我在询问用户有多少人做过销售以及他们工作了多少天后创建了一个动态数组。之后程序通过 for 循环输入数据。这里要求用户输入人名,然后询问前一天的单位数,直到第二个 for 循环达到用户在其中输入的最大天数,这是我的问题。我尝试使用二维动态数组使程序不断崩溃,所以我不确定我做错了什么。这是我的代码:

#include <iostream>
#include <string>
struct emp{
     string names;
     int *untsold;


}; 



int main(){
     int people;
     int days;
     emp *workers;
     cout<<"How many workers are we looking at?"<<endl;
     cin>>people;
     cout<<"How many days are we looking at?"<<endl;
     cin>>days
     workers = new emp[people,days];
     for(int index=0;index<people;index++){
          cin.ignore();
          cout<<"Enter the name of worker number "<<index+1<<"."<<endl;
          getline(cin,emp[index,0].names);
          for(int index2=0;index2<days;index++){
              cout<<"Now enter the number of units sold on day "<<index2+1<<endl;
              cin>>*workers[index,index2].untsold;
          }

     }



}

程序的其余部分只是在表格中显示信息,然后删除动态数组。在我为 *workers[index,index2].untsold 变量输入内容后,程序似乎立即崩溃了。是否可以将变量数组放在动态数组中,或者我应该尝试其他方法。请注意,我的老师希望我同时使用结构变量和动态数组,还请注意我是初学者。

最佳答案

对动态大小数组使用 std::vector

要实现矩阵,最简单和最有效的方法是使用单个 vector 来保存所有项,然后从矩阵中指定的 (x, y) 位置计算单个 vector 中的索引。

如果您想要 (x, y) 索引的运算符符号,请使用 operator()(它可以接受任意数量的参数),而不是 operator[](它只能接受一个参数)。技术上可能使用方括号索引的多个应用程序,但它变得复杂和快速,取决于代理对象来表示部分索引 - 所以请使用命名操作或 operator( )

关于c++ - 如何在动态数组中访问和使用动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21083809/

相关文章:

python - 获取图像中矩形的数量

C 数组错误 - 要求我声明同一个变量两次

c - 使用双指针打印

C 结构体中的增量计数器

pointers - Box,ref和&和*之间的理解和关系

C++ 可变参数模板 : remove/replace type at index

c++ - SCons StaticLibrary header 更改后未重建

c++ - 猜测运行时函数的返回类型

java - 在一行中用数组初始化 ArrayList

javascript - 如何在 http.request Node 中传递数组?