c++容器加迭代器和python装饰器的对比

2018-12-19 01:46:22来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

c++利用对象实现简单数据的测试:

class TestDataEmptyArray {
public:
    static vector<int> get_array() {
        std::vector<int> vec {};
        return vec;
    }

};

class TestDataUniqueValues {
public:
    static vector<int> get_array() {
        // declare a vector with minimum 2 values that are unique
        std::vector<int> vec {1, 2, 3, 4, 5};
        return vec;
    }

    static int get_expected_result() {
        //declare the former vector
        std::vector<int> vec {get_array()};
        //search for the smallest element with algorithm
        std::vector<int>::iterator result = std::min_element(std::begin(vec), std::end(vec));
        //return the index of the smallest element as a type int
        return std::distance(std::begin(vec), result);
    }

};

class TestDataExactlyTwoDifferentMinimums {
public:
    static vector<int> get_array() {
        //declare a vector that has atleast 2 non unique number in it
        std::vector<int> vec {1, 2, 3, 4, 3, 2, 1};
        return vec;
    }

    static int get_expected_result() {
        //declare tha former vector
        std::vector<int> vec {get_array()};
        ////search for the smallest element with algorithm
        std::vector<int>::iterator result = std::min_element(std::begin(vec), std::end(vec));
        //return the index of the smallest element as a type int
        return std::distance(std::begin(vec), result);
    }

};

python 利用装饰器进行实现

class TestDataEmptyArray(object):
    
    @staticmethod
    def get_array():
        return []

class TestDataUniqueValues(object):

    @staticmethod
    def get_array():
        arr = [2,3,4,6,5]
        return arr

    @staticmethod
    def get_expected_result():
        return 0

class TestDataExactlyTwoDifferentMinimums(object):

    @staticmethod
    def get_array():
        arr = [2,3,4,2,4]
        return arr

    @staticmethod
    def get_expected_result():
        return 0

相比较来说,python实现的代码更加简洁。

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:day 16 初试面试对象

下一篇:Python学习之旅(三十七)