比较存储在向量中的类对象的私有成员变量 - C++
Comparing the private member variables of class objects stored in a vector - C++
所以我创建了一个程序,它可以读取大约20行的.dat文件,其中包含有关不同原子的信息(名称,符号,质量等),并将它们全部添加到我制作的称为Atom的类类型的向量中。
我将如何编写一个函数来找到质量最高的原子?
这是我的班级:
class Atom
{
string element, symbol;
float number;
float mass;
public:
Atom(string e, string s, float n, float m){
element = e; symbol = s; number = n; mass = m;
}
string getElement();
string getSymbol();
float getNumber();
float getMass();
float ratio();
friend ostream& operator<<(ostream& os, Atom c);
};
并将信息添加到具有以下语句的向量中
ifstream fin("atoms.dat");
string E, S;
float M, N;
vector <Atom> periodic;
while(!fin.eof()){
fin >> E >> S >> M >> N;
Atom Atom(E, S, M, N);
periodic.push_back(Atom);
}
我希望能够编写一个函数来查找哪个原子的质量最高,我尝试使用max_element函数,但我不断收到错误。有没有一种快速的方法来比较存储在向量中的类对象的成员变量?
我目前正在使用 C++ 98,因为它是我的课程所要求的。
谢谢
我不知道
你做错了什么std::max_element
,因为你没有提供你尝试过的东西。
struct CompareAtomMass
{
bool operator()(const Atom& lhs, const Atom& rhs) {
return lhs.getMass() < rhs.getMass();
}
};
然后:
vector <Atom> periodic;
Atom max_atom = *max_element(periodic.begin(), periodic.end(), CompareAtomMax());
struct CompareAtomMass
称为函数对象。这是一个operator()
重载以返回bool
的类。 std::max_element
只需要这样一个函数对象来吐出 max 元素,因为它需要一种方法来比较您的Atom
s。
编辑:您应该将 getter 函数标记为 const
,因为它们不会更改类的内部状态。
string getElement() const;
string getSymbol() const;
float getNumber() const;
float getMass() const;
这将允许您从类型 Atom
的 const
对象调用它们,就像上面的函数对象需要 ( const Atom&
)。
DeiDeis 的变体 答案:如果你只在一个地方这样做,并且觉得不需要保留一个 CompareAtomMass 函数类,你可以使用 lambda:
const auto maxIt = max_element(periodic.begin(), periodic.end(),
[](const Atom& lhs, const Atom& rhs) {
return lhs.getMass() < rhs.getMass();
));
if(maxIt != periodic.end()){
// use *maxIt ;
}
在 C++14 及更高版本中,您还可以在 lambda 中使用 auto
:
const auto maxIt = max_element(periodic.begin(), periodic.end(),
[](const auto& lhs, const auto& rhs) {
return lhs.getMass() < rhs.getMass();
));
最好使成员函数const
。这将允许此代码。否则,只需从我的代码中删除所有const
。如果你的向量是空的,你会得到空指针。
struct AtomMassComparator
{
bool operator()(const Atom& lhs, const Atom& rhs)
{
return lhs.getMass() < rhs.getMass();
}
};
const Atom* getAtomWithHighestMass(const vector<Atom>& v)
{
vector<Atom>::const_iterator it = max_element(
v.begin(), v.end(), AtomMassComparator());
return v.end() == it ? 0 : &*it;
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 将包含C样式数组的对象初始化为成员变量(C++)
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 在循环中按顺序遍历成员变量
- c++类声明时,相同的例程,不同的成员变量类型
- 如何从另一个文件继承私有成员变量和公共函数
- 在C++类中,是否必须初始化作为数组的成员变量
- 如何从子成员函数修改父公共成员变量
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 从私有成员变量的成员方法返回unique_ptr
- 在派生类中使用基类的私有成员变量的最佳方法
- 静态 constexpr 类成员变量对多线程读取是否安全?
- C++:是否可以使用非静态成员变量模板?
- 打印所有继承的类成员变量和方法
- 如何在复杂继承中访问静态成员变量
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 成员变量与函数概念检查