如何在for循环中删除第一个结果,以便它不会重复自身

时间:2019-04-13 03:08:44

标签: c++

我正在尝试获取用户希望查看的csv文件最大变化百分比(例如:如果用户希望查看文件中3个最大变化百分比,则程序应显示)。每当我执行循环时,结果似乎就会重复。我知道我缺少了一些东西,但由于我仍在学习c ++,因此无法算得上什么

for (int x = 0; x < days; x++) {

            double original = s[0].percent_change;
            int maximum;
            //Loop that computes the stock whose percentage change increased the most

            for (int i = 0; i < lines; i++) {

                if (s[i].percent_change > original) {
                    original = s[i].percent_change;
                    maximum = i;
                }
            }
            cout << "\n\nThe greatest percent change is the date: " << endl;

            cout << s[maximum].date << endl;
            cout << s[maximum].adj_close << endl;
            cout << s[maximum].percent_change << endl;

        }
    }

//“天”实际上是用户输入的内容,也是用户希望查看的结果数。

我希望输出显示不同的结果,并且不会重复自身。

1 个答案:

答案 0 :(得分:0)

您的代码没有多大意义。在主要的for循环中,没有任何东西依赖于循环的x变量,那么为什么要进行任何更改?第二次,它的行为会有什么不同?

最简单的解决方案可能是先对数组进行排序,然后挑选顶部(或底部)days元素。

请参阅:std::sort

#include <algorithm>
#include <functional>
#include <array>
#include <iostream>

int main()
{
    std::array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; 

    // sort using the default operator<
    std::sort(s.begin(), s.end());
    for (auto a : s) {
        std::cout << a << " ";
    }   
    std::cout << '\n';

    // sort using a standard library compare function object
    std::sort(s.begin(), s.end(), std::greater<int>());
    for (auto a : s) {
        std::cout << a << " ";
    }   
    std::cout << '\n';

    // sort using a custom function object
    struct {
        bool operator()(int a, int b) const
        {   
            return a < b;
        }   
    } customLess;
    std::sort(s.begin(), s.end(), customLess);
    for (auto a : s) {
        std::cout << a << " ";
    }   
    std::cout << '\n';

    // sort using a lambda expression 
    std::sort(s.begin(), s.end(), [](int a, int b) {
        return a > b;   
    });
    for (auto a : s) {
        std::cout << a << " ";
    } 
    std::cout << '\n';
}