自定义过滤器功能不会产生预期的输出

标签 c filter

我正在尝试制作一个过滤器,它只在屏幕上打印我想要的数据。这就是我要说的:

Cost* FilterSum(Controller* ctrl, int n)
{
    int i;
    DynamicVector* CostList=getAll(ctrl->repo);
    for(i=0;i<getLen(CostList);i++)
    {
        Cost* c=getElementAtPosition(CostList,i); //returns the element on one position
        if((c->sum)<n)
        {
            return c; //if the element(Cost in my case) has the sum<20 return it
        }
    }


return 0;
}

所以,我有一个以成本为元素的动态数组。如果成本总和小于 n(n 从键盘给出),我只想在屏幕上打印那些成本。 :) 这是控制台中的打印功能:

void PrintCost(Cost* c) //this function prints one cost
{
    printf("\nID: %d\n", getID(c));
    printf("Day: %s\n", getDay(c));
    printf("Type: %s\n", getType(c));
    printf("Sum: %d\n\n", getSum(c));
}

void PrintCosts(Console* console) //this one prints all the costs in the list
{
    DynamicVector* CostList=getAllCosts(console->ctrl);
    if (getLen(CostList))
    {
        int i;
        for(i=0;i<getLen(CostList);i++)
        {
            Cost *c=(Cost*)getElementAtPosition(CostList,i);
            PrintCost(c);
        }

    }
    else printf("No cost in the list!");
}

这是控制台中 Controller 的调用函数:

void FilterCostsBySum(Console* console)
{
    int n;
    printf("See the costs that have the sum less than: ");
    scanf("%d",&n);
    Cost* c = FilterSum(console->ctrl,n);
    PrintCost(c);
}

现在,问题来了。如果我有 sum=10 的星期一,sum=20 的星期五和 sum=40 的星期六,我只想打印 sum<30 的那几天,它只打印星期一,仅此而已,它也不会打印星期五。我哪里做错了?在我返回 c? 的 Controller 的 FilterSum 函数中我什么都试过了,但一点用都没有……也许你能帮帮我! :)

最佳答案

它只打印一个,因为在通过 FilterSum 获得有效成本之一后,您只执行一次 PrintCost 函数。您需要使 FilterCostsBySum 函数循环并将打印成本推送到 DynamicVector

编写一个函数,该函数返回一个 DynamicVector,其中包含满足您所需条件的所有成本。您可以通过更改 FilterSum 函数来执行此操作,这样它不会返回一个 Cost,而是将满足给定条件的任何成本添加到 DynamicVector 并返回。之后重命名函数 GetFilteredCosts

最后,在 FilterCostsBySum 函数中,您将遍历返回的 DynamicVector 中的元素并打印成本。

关于自定义过滤器功能不会产生预期的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15507265/

相关文章:

c - 你应该释放传递给 prctl() 的内存吗?

elasticsearch - 嵌套对象的 boolean 过滤器

JavaScript/jQuery 可以做一些改进

php - 过滤购物网站的搜索结果

c - 尝试通过使用字符串来检查数字是否为回文

c - 使用 setuid 降低到较低权限级别的正确方法是什么?

c - C 中带有字符串的双指针/使用 malloc 指向数组的指针

python - 如何在 python 中使用 ctypes 重载 C 库的弱声明函数?

c# - 带有参数化 IN 子句的 FluentNHibernate 过滤器

mysql - 使用 MySQL 对连接表应用过滤器