Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/134.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
如何将对象类型转换为int C++_C++_Class_Object_Oop_Integer - Fatal编程技术网

如何将对象类型转换为int C++

如何将对象类型转换为int C++,c++,class,object,oop,integer,C++,Class,Object,Oop,Integer,我试图使用两个类创建一种记录列表。一个类用于输入值,而另一个类用于收集、组织和打印值。这是我的密码: class enterrecords { public: string name; int age; string birthmonth; enterrecords() { name = ""; age = 0; birthmonth = ""; }

我试图使用两个类创建一种记录列表。一个类用于输入值,而另一个类用于收集、组织和打印值。这是我的密码:

   class enterrecords
{
public:
    string name;
    int age;
    string birthmonth;

    enterrecords() 
    {
        name = "";
        age = 0;
        birthmonth = "";
    }
    enterrecords(string n, int a, string b) 
    {
        name = n;
        age = a;
        birthmonth = b;
    }

};
class records 
{
public:
    vector <enterrecords> list;
    records() 
    {

    }
    records(enterrecords s) 
    {

    }
    void addtolist(const enterrecords s)
    {
        this->list.push_back(s);
    }
    void print()
    {
        for (const auto& it : this->list)
        {
            cout << it.name << " " << it.age << " " << it.birthmonth << endl;
        }
    }
};

int main() 
{
    enterrecords s1;
    enterrecords s2;
    enterrecords s3;
    records c1;
    s1 = enterrecords("john", 21, "jan");
    s2 = enterrecords("male", 25, "feb");
    s3 = enterrecords("rob", 23, "oct");
    c1.addtolist(s1);
    c1.addtolist(s2);
    c1.addtolist(s3);
    c1.print();
}
以下是该程序的输出:

约翰1月21日

男2月25日

罗伯10月23日

最终,我希望能够按照年龄从最小到最大来组织这个列表。因此,在重新排列它们之后,下面是它之后的样子:

约翰1月21日

罗伯10月23日

男2月25日

我尝试按常规对它们进行排序,但问题是,2123和25不是int值,而是对象值。有没有办法将它们转换成int,这样我就可以进行一些操作并对它们进行排序?谢谢。

通常用于对对象序列进行排序。要么类有一个自然顺序,然后为它生成一个运算符<函数,最好是其他布尔比较运算符,要么将一个比较器函数传递给std::sort,该函数可以是lambda,用于比较一个或两个成员变量之类的简单比较

基于未编译/测试的代码的示例,不考虑月份,因为您使示例更难:

std::sort(c1.list.begin(), c1.list.end(), [](const auto& r1, const auto& r2) { return r1.age < r2.age; });

不确定你所说的对象值是什么意思。年龄是一个整数。要按年龄对向量排序,使用std::sort和一个比较器,该比较器接受对两个enterrecords对象的引用,如果第一个年龄小于第二个年龄,则返回true。谢谢,先生,有没有任何方法可以通过代码来证明这一点?因此,如果我使用它,它将重新排列列表本身,或者它将只说r1.age