如何创建类对象的向量

How to create a vector of class objects

本文关键字:对象 向量 创建 何创建      更新时间:2023-10-16

我正在尝试创建一个包含各种课程时间的向量。之后,我将比较这些时间,以查看哪个是通过排序函数较早的。

编辑:提到了一些人,我确实希望使用旧版本的C (11之前(进行此操作,因为这是我的教练要求的

是否有一种方法可以使用push_back?

到目前为止,我的主文件中有一个:

std::vector<Time> times (Time t1(4,5,4), Time t2(3,5,4));
std::sort(times.begin(), times.end(), IsEarlierThan);

在我的时间中。cpp文件:

#include <iostream>
#include "Time.h"
Time::Time() {
    hour = 0;
    minute = 0;
    second = 0;
}
Time::Time(int theHour, int theMinute, int theSecond) {
    hour = theHour;
    minute = theMinute;
    second = theSecond;
}
int Time::getHour() const {
    return hour;
}
int Time::getMinute() const {
    return minute;
}
int Time::getSecond() const {
    return second;
}
bool IsEarlierThan(const Time& t1, const Time& t2){
    if (t1.getHour() < t2.getHour()) return true;
    else if (t1.getHour() == t2.getHour()){
        if (t1.getMinute() < t2.getMinute()) return true;
        else if (t1.getMinute() == t2.getMinute()){
            if(t1.getSecond() < t2.getSecond()) return true;
        }
    } 
    return false;
}

矢量声明不正确,所以我的问题是我将如何添加这些时间(包括小时,分钟和第二次(作为单独的向量值,并将它们彼此进行比较(例如,比17:23:56早于17:23:5619:49:50(。

iSearlierthan函数有效,尽管我不确定如何使用向量实现它。

感谢您的任何帮助!

矢量声明是正确的,vector construction 不正确。 std::vector没有接受向量元素类型的两个参数的构造函数。

如果要使用代码中的值初始化vector,请将此行更改为:

std::vector<Time> times {Time(4,5,4), Time(3,5,4)};

请参阅列表初始化,以获取详细说明,其在引擎盖下的工作方式。

编辑:

对于早于C 11星级 - 请参阅此帖子。

,或者如果您不明确地关心这个单词的评估 - 只需使用push_back

std::vector<Time> times;      // create an empty vector
times.push_back(Time(4,5,4)); // append element to vector
times.push_back(Time(3,5,3));