如何创建类对象的向量
How to create a vector of class objects
我正在尝试创建一个包含各种课程时间的向量。之后,我将比较这些时间,以查看哪个是通过排序函数较早的。
编辑:提到了一些人,我确实希望使用旧版本的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));
相关文章:
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 从多个源构造一个对象,包括一个对象向量
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 对象 C++ 向量的 STL 容器
- 初始化C++中的对象向量
- 从自定义类获取对象向量中的 max 元素
- 如何在 c++ 中打印存档中的对象向量
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 尝试重载输出运算符时,我无法遍历对象向量
- 如何在C++中打印对象向量的内容
- 打印出对象向量中的每个元素C++
- 在 c++ 的构造函数中分配对象向量时出错
- 遍历对象向量,并找到与从文本文件中提取的对象匹配的变量
- 对象向量是否在堆或堆栈上分配C++?
- 基于不同字段的对象向量的排序功能
- 有没有一种简单的方法可以在对象向量上调用构造函数?
- 用rapidjson读取子对象向量
- 尝试使用比较运算符对对象向量进行排序
- 如何用对象向量重载 cin(>>)
- 如何将某个元素从shared_ptr擦除到对象向量?