Comparison tricks in C++

前端 未结 10 1854
礼貌的吻别
礼貌的吻别 2021-01-31 16:13

A class:

class foo{
public:
    int data;
};

Now I want to add a method to this class, to do some comparison, to see if its data is equal to on

10条回答
  •  余生分开走
    2021-01-31 16:35

    I would recommend to use standard container like std::vector, but that would still imply a linear complexity with worst-case runtime of O(N).

    class Foo{
    public:
        int data;
        bool is_equal_to_one_of_these(const std::vector& arguments){
            bool matched = false;
            for(int arg : arguments){ //if you are not using C++11: for(int i = 0; i < arguments.size(); i++){
                if( arg == data ){ //if you are not using C++11: if(arguments[i] == data){
                    matched = true;
                }
            }
            return matched;
        }
    };
    
    std::vector exampleRange{ {1,2,3,4,5} };
    Foo f;
    f.data = 3;
    std::cout << f.is_equal_to_one_of_these(exampleRange); // prints "true"
    

提交回复
热议问题