在某些条件下找到不同于零的最小值

时间:2014-04-12 21:17:14

标签: c++ algorithm stl iterator set

我已经开始学习C++ SetsIterators而我无法确定我是否正确地做了这个,因为我相对来说编程新手。

我已经使用自定义比较器创建了Setstruct,该比较器将项目按递减顺序排列。在收到输入之前,我不知道我的Set将包含多少项。它可以包含01000中的任意数量的项目。

以下是Set定义:

typedef struct Pop {
    int value_one; int node_value;
} Pop;

struct comparator {
    bool operator() (const Pop& lhs, const Pop& rhs) const {
        if (rhs.value_one == lhs.value_one) {
            return lhs.node_value < rhs.node_value;
        } else { return rhs.value_one < lhs.value_one;}
    }
};

set<Pop, comparator> pop;
set<Pop>::iterator it;

这就是算法。它应该找到minimum值并打印该值。如果找不到(函数do_some_work(...)返回0),则应该打印"Zero work found!\n"

int minimum = (INT_MAX) / 2; int result;

int main(int argc, char** argv) {
    //....
    //After reading input and adding values to the SET gets to this part
    Pop next;
    Pop current;
    for (it = pop.begin(); it != pop.end() && minimum != 1; it++) {
        current = *it;
        temp_it = it;
        temp_it++;
        if (temp_it != pop.end()) {
            next = *temp_it;
            // This function returns a integer value that can be any number from 0 to 5000.
            // Besides this, it checks if the value found is less that the minimum (declared as global)  and different of 0 and if so
            // updates the minimum value. Even if the set as 1000 items and at the first iteration the value
            //  found is 1, minimum is updated with 1 and we should break out of the for loop.
            result = do_some_work(current.node_value); 
            if (result > 0 && next.value_one < current.value_one) {
                break;
            }
        } else {
            result = do_some_work(current.node_value); 
        }
    }
    if (minimum != (INT_MAX) / 2) {
        printf("%d\n", minimum);
    } else {
        printf("Zero work found!\n");
    }
    return 0;
}

以下是一些可能的结果。

如果Set为空,则应打印Zero work found!

如果Set作为一个项目而do_some_work(current.node_value)返回的值大于0,则应printf("%d\n", minimum);Zero work found!

想象一下,我有Set(第一个位置value_one和第二个位置node_value

4 2
3 6
3 7
3 8
3 10
2 34
  • 如果在第一次迭代中do_some_work(current.node_value)返回的值大于0,因为所有其他项value_one都较小,它应该打破循环,打印minimum和退出程序。
  • 如果在第一次迭代中do_some_work(current.node_value)返回0,我会前进Set,因为4value_one3 4我必须分析这个minimum项,因为其中任何一项都可以返回可能的有效minimum值。如果其中任何一项将1值更新为minimum,则应该打破循环,打印Set并退出程序。
  • 在这种情况下,仅当所有其他项目返回0minimum值设置为1时,才会分析minimum的最后一项。

对我来说,这既是算法问题又是编程问题。

使用此代码,我是否正在分析所有可能性,如果11,则打破循环,因为如果返回{{1}},那么就没有必要检查任何其他项目?

0 个答案:

没有答案