0

我正在为我的 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 来做。现在让我感到困惑的最大的事情(以所做的方式就是为什么数据文件没有传递到向量中)

4

1 回答 1

2

由于您不知道文件中有多少不同的值,因此您有两个选择:resize必要时使用向量,或使用map. 后者是解决此问题的最简单方法:

std::map<unsigned, unsigned> numbers;

while(frequency >> data)
{
    numbers[data]++;
}

如果您想再次遍历数字,可以使用您当前的方法。但是,这将导致将其他条目添加到您的地图中(查看std::map::operator[])。但是,您可以使用iterators仅显示已添加到地图中的值:

for(
    std::map<unsigned, unsigned>::iterator it = numbers.begin(); 
    it != numbers.end();
    it++
){    
    cout << setw(3) << it->first <<": " << it->second << endl;
}

如果您被允许使用 C++11,那么使用 range-for-loops 会变得更加简单:

for(auto entry : numbers){
{    
    cout << setw(3) << entry.first <<": " << entry.second << endl;
}
于 2013-03-28T20:21:11.027 回答