我只是在学习C ++类,并且正在尝试比较和排序矢量值(时间早于其他时间),而其他一切都有效,而矢量中的最后一个值不会被打印出来。我猜测它与我的主要功能中的for循环有关,但我不能自己解决。
感谢您的帮助!
的main.cpp
#include <iostream>
#include "Time.h"
#include <vector>
#include <algorithm>
int main() {
std::cout << "Please enter hour, minute, second: ";
int hour, minute, second;
std::cin >> hour >> minute >> second;
Time now(hour, minute, second);
//random time values
Time now1(13,1,45);
Time now2(23,47,12);
Time now3(1,8,8);
Time now4(19,4,13);
std::vector<Time> times;
times.push_back(now1);
times.push_back(now);
times.push_back(now2);
times.push_back(now3);
times.push_back(now4);
sort(times.begin(), times.end(), IsEarlierThan);
for(unsigned int i = 0; i < times.size(); i++){
//std::cout << times[i] << std::endl;
times[i].PrintAmPm();
}
return 0;
}
Time.cpp
#include <iostream>
#include <string>
#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;
}
void Time::PrintAmPm() const {
int hour1;
std::string amOrPm;
if ((hour >= 0) && (hour <= 11))
amOrPm = "am";
else
amOrPm = "pm";
if ((hour > 12) && (hour <= 23))
hour1 = hour - 12;
if (hour == 0)
hour1 = hour + 12;
if ((hour > 0) && (hour <= 12))
hour1 = hour;
if ((minute < 10) && (second >=10))
std::cout << hour1 << ":0" << minute << ":" << second << amOrPm << std::endl;
if ((minute < 10) && (second < 10))
std::cout << hour1 << ":0" << minute << ":0" << second << amOrPm << std::endl;
if ((minute >= 10) && (second < 10))
std::cout << hour1 << ":" << minute << ":0" << second << amOrPm << std::endl;
}
bool IsEarlierThan(const Time& t1, const Time& t2){
if (t1.getHour() < t2.getHour())
return true;
if ((t1.getHour() == t2.getHour()) && (t1.getMinute() < t2.getMinute()))
return true;
if ((t1.getHour() == t2.getHour()) && (t1.getMinute() == t2.getMinute())
&& (t1.getSecond() < t2.getSecond()))
return true;
else
return false;
}
时间。 ħ
class Time {
public:
Time();
Time(int theHour, int theMinute, int theSecond);
int getHour() const;
int getMinute() const;
int getSecond() const;
void PrintAmPm() const;
private:
int hour;
int minute;
int second;
};
bool IsEarlierThan(const Time& t1, const Time& t2);
答案 0 :(得分:1)
您没有看到其中一个输出,因为您的测试从未在minutes >= 10
和second >= 10
时打印。
if ((minute < 10) && (second >=10))
if ((minute < 10) && (second < 10))
if ((minute >= 10) && (second < 10))
// None of these handle minute >= 10 && second >= 10!
now2
有两位数分钟和秒,因此您的打印方法无效。
真的,这里正确的解决方案是只需使用cout
std::cout << std::setfill('0')
<< hour1 << ':'
<< std::setw(2) << minute << ':'
<< std::setw(2) << second << amOrPm << std::endl;
替换这些测试,使用std::setfill
和std::setw
来对齐输出,而无需手动/有条件地归零。
minute
无需检查second
/ cout
的范围,您只是无条件告诉0
应使用char
填充,并设置所需的宽度以填充to(需要每次都设置,因为输出const m = moment.tz("01/01/2019 5:30pm", "MM/DD/YYYY h:mma", true, "invalid timezone");
m.isValid(); //true
会重置宽度)。