Mariankka
Mariankka

Reputation: 89

How to create a vector of class objects

I'm trying to create a vector that contains various class times. Afterwards, I would compare these times to see which one is earlier through a sorting function.

Edit: after some people mentioned, I do wish to do this with an older version of C++ (prior to 11) because it's what my instructor requested

Would there be a way to do this with push_back?

So far, I have this in my main file:

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

and this in my Time.cpp file:

#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;
}

The vector declaration is not correct, so my question would be how would I add these times (including hour, minute, and second) as separate vector values and compare them to each other (eg is 17:23:56 earlier than 19:49:50).

The IsEarlierThan function works, though I am unsure of how to implement it with a vector.

Thanks for any help!

Upvotes: 0

Views: 301

Answers (1)

k.v.
k.v.

Reputation: 1223

Vector declaration is correct, vector construction is incorrect. std::vector does not have a constructor which accepts two arguments of vector's element type.

If you want to initialize vector with the values from your code - change this line to:

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

See list initialization for detailed explanation how it works under the hood.

Edit:

For earlier than C++11 stardard - see this post.

Or if you don't care about this explicitly to be a single-statement assingment - just use 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));

Upvotes: 2

Related Questions