比较存储在向量中的类对象的私有成员变量 - C++

Comparing the private member variables of class objects stored in a vector - C++

本文关键字:成员 变量 C++ 存储 向量 比较 对象      更新时间:2023-10-16

所以我创建了一个程序,它可以读取大约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;

这将允许您从类型 Atomconst 对象调用它们,就像上面的函数对象需要 ( 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;
}