我正在为我的 C++ 类进行分配,并且在使用 ifstream 的 while 循环中将数据传递给向量时遇到了麻烦。
这就是我最终这样做的方式,它有效,但取决于数据文件小于 100 个整数:
void Frequency()
{
ifstream frequency("test.dat");
if (! frequency)
{
cout << "**Error opening File**";
}
else
{
int data;
vector <int> numbers(101, 0);
while(frequency >> data)
{
numbers[data-1] += 1;
}
for(int i = 100; i >= 1; i--) //
{
if (numbers[i] != 0)
{
cout << setw(3) << i+1 <<": " << numbers[i] << endl;
}
}
}
}
它按降序返回某些数字的频率。
这感觉更像是我在通过它而不是在编码,虽然(尽管我的教练坚持“这是简单的方法!”我不想要简单,我想要正确。我这样做是这样的:
void Frequency()
{
ifstream frequency("test.dat");
if (! frequency)
{
cout << "**Error opening File**";
}
else
{
int size = 0;
int x; //actually a useless variable, only exists so the program can iterate to find the size
while (frequency >> x) //gives us the size of the data file
{
size++;
}
vector <int> numbers(size, 0);
int data;
int a = 0;
while (frequency >> data) //inputs the data into the vector
{
numbers[a] = data;
a++;
}
for (int a = 0; a < size; a++)
{
frequency >> numbers[a];
}
for(int i = 0; i < size; i++) //displays each subvector and it's value (for testing)
{
cout << "numbers[" << i << "]: " << numbers[i] << endl;
}
}
}
但是所有向量都返回为 0。任何人都可以看到为什么数据没有正确通过吗?
这是我传递的数据文件,供参考。75 85 90 100
60 90 100 85 75 35 60 90 100 90 90 90 60 50 70 85 75 90 90 70
编辑:修复了一些评论的东西。我一定会尝试用 MAP 来做。现在让我感到困惑的最大的事情(以我所做的方式就是为什么数据文件没有传递到向量中)