如何创建类对象的向量

时间:2017-06-23 18:29:41

标签: c++ class sorting vector c++03

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

编辑:在一些人提到之后,我确实希望用旧版本的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);

这在我的Time.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)十九时49分50秒)。

IsEarlierThan函数有效,但我不确定如何使用向量实现它。

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

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

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

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

请参阅list initialization详细说明如何在幕后工作。

修改

早于C ++ 11标准 - 请参阅this post

或者,如果您不明白这是单一陈述分配 - 只需使用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));