C++ comparing bunch of values with a given one

后端 未结 10 929
一向
一向 2021-01-21 06:02

I need to compare one given value with a retrieved values. I do this several times in the code. I am not satisfied with how it looks and I am seeking for a some sort of an util

10条回答
  •  一向
    一向 (楼主)
    2021-01-21 06:50

    You don't need a std::set or a std::vector. Just use std::set_intersection()...

    Code is best...

    #include 
    #include 
    #include 
    using namespace std;
    
    #define COUNT(TYPE,ARRAY)  ( sizeof(ARRAY) / sizeof(TYPE) )
    
    inline bool CaseInsensitiveCompare (const char * a, const char * b)
      {  return strcasecmp( a, b ) < 0;  }
    
    int  main()
    {
      const char * setA[] = { "the", "world", "is", "flat" };
      const char * setB[] = { "the", "empty", "set", "is", "boring" };
    
      stable_sort( setA,  setA + COUNT( const char *, setA ),
                   CaseInsensitiveCompare );
    
      stable_sort( setB,  setB + COUNT( const char *, setB ),
                   CaseInsensitiveCompare );
    
      cout << "Intersection of sets:  ";
      set_intersection( setA, setA + COUNT( const char *, setA ),
                        setB, setB + COUNT( const char *, setB ),
                        ostream_iterator(cout, " "),
                        CaseInsensitiveCompare );
      cout << endl << endl;
    }
    

    Or perhaps, given your 1-N lookup problem:
    (Note: Use binary_search() AFTER sorting!)

    if ( binary_search( setA, setA + COUNT( const char *, setA ),
                "is", CaseInsensitiveCompare ) )
      ...
    
    if ( binary_search( setA, setA + COUNT( const char *, setA ),
                "set", CaseInsensitiveCompare ) )
      ...
    

提交回复
热议问题