我正尝试在我的 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/