C ++ 11 - 在数字向量

时间:2017-01-07 12:54:47

标签: c++ c++11 vector calculator mode

我正在开发一个程序,在给定输入文件中的值列表(double s)的情况下,按升序对它们进行排序并计算mode,并将结果打印在输出文件。这就是我到目前为止所提出的。

它应该做的是将模式分配给向量的x元素,即为current产生更大值的元素,但是当我运行此程序时,模式始终等于向量的最后一个元素。

我无法弄清楚我在做什么错误,因为在我看来它似乎完全符合逻辑。

非常感谢任何帮助。

#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <fstream>
using namespace std;

int main()
{
    ifstream iFile("inp.txt");
    if(!iFile)
    {
        cout << "Error input!" << endl;
        return -1;
    }

    ofstream oFile("out.txt");
    if(!oFile)
    {
        cout << "Error output!" << endl;
        return -1;
    }

    double data;
    vector<double> list;

    while(iFile >> data)
    {
        list.push_back(data);               //put the elements in a vector
        sort(list.begin(), list.end());     //and sort them in ascending order
    }

    for(int m = 0; m < list.size(); ++m)    //this is just
    {                                       //to verify
        oFile << list[m] << endl;           //that the elements
    }                                       //are listed in order

    int current = 0;
    int previous = 0;
    int mode = 0;
    for(int x = 0; x < list.size(); ++x)        //select an element of the vector
    {
        for(int y = 0; y < list.size(); ++y)    //match it against all the other elements of the vector
        {
            if(list[x] == list[y])              //if they're of equal value
            {
                ++current;                      //add 1 to variable "current"
            }
        }

        if(current > previous)                  //if "current" > "previous"
            {
                mode = list[x];                 //set the element "x" (from the first for) of the vector "list" to be the new mode
                current = previous;             //and set current to be the new previous    
            }

        current = 0;                            //reset current to 0
    }

    oFile << "\nmode: " << mode << endl;        //output "mode"

    return 0;
}

1 个答案:

答案 0 :(得分:1)

尝试

previous = current;

而不是

current = previous;

在上一个if中,或previous为零,最后x(当y等于x时与自身匹配)生成current大于previous(即零)。

OT:看看这个while

while(iFile >> data)
{
    list.push_back(data);               //put the elements in a vector
    sort(list.begin(), list.end());     //and sort them in ascending order
}

每次插入后都无需对矢量进行排序。我建议你在list中添加输入文件的所有内容,然后对矢量进行排序。只有一次,仅在最后一次插入后。

这样的东西
while(iFile >> data)
{
    list.push_back(data);  //put the elements in a vector
}

sort(list.begin(), list.end()); //and sort them only one time