首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何为用户定义的数据类型使用包含<algorithm>的STL

如何为用户定义的数据类型使用包含<algorithm>的STL
EN

Stack Overflow用户
提问于 2013-10-24 09:07:05
回答 1查看 142关注 0票数 0

我有一节简单的课

代码语言:javascript
复制
class sample
{
    int i;

    public:
    sample(int i): i(i){}

};

int main()
{  
    cout << max (12, 26) << endl; // working fine
    sample s1(10), s2(20);
    cout << max (s1, s2);  // lots of compilation errors
    return 0; 
}

我希望max (s1,s2)应该返回最大值(s1,s2)。我知道我错过了一些东西,但无法想象这些东西。

任何帮助都将不胜感激。

德韦什

EN

回答 1

Stack Overflow用户

发布于 2013-10-24 09:14:33

代码语言:javascript
复制
class sample
{

    public:
    int i;
    sample(int i): i(i){}
    bool operator< (const sample& other) const
    {
        return i < other.i;
    }

};

int main()
{  
    sample s1(10), s2(20);
    max (s1, s2); 
    return 0; 
}

注意constoperator <之后,这是很重要的。:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19561557

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档