Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/126.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用给定比较器查找给定范围内的最小模板对象_C++_Templates_Lambda_Comparator - Fatal编程技术网

C++ 使用给定比较器查找给定范围内的最小模板对象

C++ 使用给定比较器查找给定范围内的最小模板对象,c++,templates,lambda,comparator,C++,Templates,Lambda,Comparator,我正在实现一个存储模板对象向量的类。目标是使用默认的std::less比较器或在构造函数参数中传递的可选比较器来查找给定范围内的最小值。传递的比较器是函子、函数或lambda函数 如何使用给定的比较器在给定范围内(由两个迭代器设置)查找对象的最小值 我知道,对象实现了重载操作符b; } ); for(const auto&w:words) D推回(w); */ //断言(d.min(d.begin(),d.end())=“voo”);//失败 /*我不知道如何接受lamba表达式 输入MyCla

我正在实现一个存储模板对象向量的类。目标是使用默认的
std::less
比较器或在构造函数参数中传递的可选比较器来查找给定范围内的最小值。传递的比较器是函子、函数或lambda函数

如何使用给定的比较器在给定范围内(由两个迭代器设置)查找对象的最小值

我知道,对象实现了重载
操作符b;
} );
for(const auto&w:words)
D推回(w);
*/
//断言(d.min(d.begin(),d.end())=“voo”);//失败
/*我不知道如何接受lamba表达式
输入MyClass成员模板变量(m_comparator)*/
返回0;
}

您显示的代码中有许多错误:

  • 将MyComparator的默认类型设置为错误的类型
    T
    是矢量元素类型,而不是比较器类型

  • =default
    应用于模板化构造函数。您将
    模板
    应用于错误的构造函数

  • findMin()上缺少
    模板
    。就这一点而言,为什么
    findMin()
    要使用迭代器,而忽略
    向量的构造函数

  • 实例化
    MyClass
    对象时不指定模板参数

  • myComparClass
    的对象传递给
    MyClass
    时未实例化该对象

  • 未将MyComparClass的成员声明为公共

  • 话虽如此,请尝试类似的方法:

    模板//可选比较器
    类MyClass
    {
    公众:
    MyClass()=默认值;
    模板
    MyClass(MyComparator comparator、MyIterator start、MyIterator end):m_comparator(comparator)
    {
    for(MyIterator it=start;it!=end;it++)
    {
    m_objects.push_back(*it);
    }
    }
    模板
    T findMin(MyIterator from,MyIterator to)
    {
    自动结果=标准::最小元素(从、到、m_比较器);
    返回*结果;
    }
    私人:
    MyComparator m_比较仪;
    向量m_对象;
    };
    //====================================================================================
    bool MyStringComparator(常量字符串和第一个、常量字符串和第二个)
    {
    返回strcasecmp(第一个.c_str(),第二个.c_str())<0;
    }
    //====================================================================================
    结构MyComparClass
    {
    MyCompareClass()=默认值;
    布尔运算符()(常量MyObject和obj1、常量MyObject和obj2)常量
    {
    返回。。。;
    }
    };
    // ========================================================
    int main()
    {
    // 1.
    向量向量{“你好”、“世界”、“你好”、“你”、“很好”、“谢谢”};
    MyClass a(&MyStringComparator,vec.begin(),vec.end());
    自动结果=a.findMin(vec.begin()+1,vec.begin()+3);/*我需要在任何对象的给定范围内找到最小值*/
    // 2. 
    向量另一个向量{MyObject_1,MyObject_2,MyObject_3,…};
    MyClass b(MyCompareClass{},anotherVec.begin(),anotherVec.end());
    自动结果_2=b.findMin(另一个vec.begin(),另一个vec.end());
    //等等。。
    返回0;
    }
    

    您一次编写的代码太多了。坦白地说,有太多的错误,我不知道从哪里开始()。要找到向量中的最小元素,可以使用“谢谢”。我已经更新了代码,但是下面的lambda表达式仍然不被接受。这是我家庭作业的一部分,所以它必须通过几项鉴定。抱歉,长度太长。@JosefMalek不接受。具体是什么原因?由编译器完成?是你的导师吗?到底是什么样的断言?我已经弄明白了。非常感谢。
    #include <iostream>
    #include <cassert>
    #include <vector>
    #include <stdexcept>
    #include <string>
    #include <algorithm>
    #include <cstring>
    #include <functional>
    
    
    using namespace std;
    
    template<typename T, typename MyComparator = std::less<T>> // optional comparator
    class MyClass
    {
    public:
        MyClass ( ) = default;
    
        template<typename MyIterator>
        MyClass ( MyIterator start, MyIterator end,  MyComparator comparator ) : m_comparator ( comparator )
        {
            for ( MyIterator it = start; it != end; it++ )
                m_objects.push_back ( * it );        
        }
        
        template<typename MyIterator>
        MyClass ( MyIterator start, MyIterator end )
        {
            for ( MyIterator it = start; it != end; it++ )
                m_objects.push_back ( * it );
        }
    
        template<typename MyIterator>
        T min ( MyIterator from, MyIterator to )
        {
            if ( from == to )
                throw invalid_argument ("Invalid");
            auto result = std::min_element ( from, to, m_comparator );
            return *result;
        }   
      typename vector<T>::iterator begin() { return m_objects.begin(); }
      typename vector<T>::iterator end() { return begin() + m_objects.size(); }
      size_t size () const { return m_objects.size(); }
      void push_back ( const T & elem ) { m_objects.push_back ( elem ); }
      void pop_back ( ) { m_objects.pop_back( ); }
    
    private:
       MyComparator m_comparator;
       // function<bool(T, T)> m_comparator;  This is not working.
        vector <T> m_objects;
        typename vector<T>::iterator const_iterator;
    };
    //-------------------------------------------------------------------------------
    class CompareClass
    {
      public:
                   CompareClass ( bool byLength = true ) 
          : m_ByLength ( byLength ) 
        { 
        }
        bool       operator () ( const string & a, const string & b ) const 
        { 
          return m_ByLength ? a . length () < b . length () : a < b;
        }
      private:
        bool       m_ByLength;  
    };
    //-------------------------------------------------------------------------------------------------
    bool CompareFun ( const string & a, const string & b )
    {
      return strcasecmp ( a . c_str (), b . c_str () ) < 0;
    }
    
    int main ( )
    {
      vector<string> words { "abc", "iff", "voo", "STACK" };
    
      MyClass <string> a ( words . begin (), words . end () );
      assert ( a . min ( a . begin (), a . end () ) ==  "STACK" );  // OK
    
      MyClass <string, bool(*)(const string &, const string &)> b ( words . begin (), words . end (), CompareFun );
      assert ( b . min ( b . begin (), b . end () ) == "abc" ); // OK
    
      MyClass <string, CompareClass> c ( words . begin (), words . end (), CompareClass ( false ) );
      assert ( c . min ( c . begin (), c . end () ) == "STACK" ); // OK
    
    /* MyClass <string, function<bool(const string &, const string &)> > d ( [] ( const string & a, const string & b )
      {
        return a > b;
      } );
      for ( const auto & w : words )
        d . push_back ( w );
    */
    
    // assert ( d . min ( d . begin (), d . end () ) == "voo" ); // Fail
    
    /* I am not able to figure out how to accept lamba expression
     into MyClass member template variable (m_comparator). */
     return 0;
    }