创建唯一对象列表

时间:2017-07-26 09:32:23

标签: c++ qt

我有一个对象.ion-ios-pin{ vertical-align: top; width: 12px; } .item-inner span { display: inline-block; width: calc(100% - 15px); float: right; white-space: normal; } 实例的QVector,其中每个Atom实例包含一组笛卡尔坐标和一个唯一索引标识符,以及其他属性。我还定义了一个Atom容器,它只是两个Dyad个实例的元组。基本上,如果我的两个Atom实例满足距离约束,我希望能够构造Atom s的QList。

假设我有DyadDyadAtom1),我怎样才能确保我的QList尚未包含(Atom2,{{Dyad} 1}})?

我已经尝试使用QList Atom2函数并重载了我的Atom1运算符,但我无法使其工作。我可以附加我尝试使用.contains()函数的代码,如果这样做有帮助的话。

//功能定义

==

contains()

1 个答案:

答案 0 :(得分:1)

我不确定我确切知道你的AtomAtomDyad类是怎样的,但我会在一个简单的例子中模仿它们,以帮助你理解。我假设Atom有三个坐标:x,y和z。我们现在编码:

struct Atom
{
  Atom(float x, float y, float z)
    : m_x(x), m_y(y), m_z(z)
  {}
  float m_x;
  float m_y;
  float m_z;

  // Sort first by x, than by y and finally by z coordinates.
  bool operator<(const Atom &other) const
  {
    if (m_x < other.m_x)
    {
      return true;
    }
    else if (m_x == other.m_x)
    {
      if (m_y < other.m_y)
      {
        return true;
      }
      else if (m_y == other.m_y)
      {
        if (m_z < other.m_z)
        {
          return true;
        }
      }
    }
    return false;
  }

  // To compare two atoms.
  bool operator==(const Atom &other) const
  {
    return m_x == other.m_x && m_y == other.m_y && m_z == other.m_z;
  }
};

现在让我们定义由AtomeDyad

组成的Atoms
struct AtomDyad
{
  AtomDyad(const Atom &a1, const Atom &a2)
    : m_a1(a1), m_a2(a2)
  {}
  Atom m_a1;
  Atom m_a2;

  bool operator<(const AtomDyad &other) const
  {
    if (m_a1 == other.m_a2 && m_a2 == other.m_a1)
    {
      return false;
    }

    if (m_a1 < other.m_a1)
    {
      return true;
    }
    else if (m_a1 == other.m_a1)
    {
      if (m_a2 < other.m_a2)
      {
        return true;
      }
    }
    return false;
  }  
};

最后,让我们存储唯一的AtomDyads。单元测试:

std::set<AtomDyad> uniqueAtomDyad;

Atom a1(0, 0, 0);
Atom a2(0, 0, 1);
Atom a3(0, 1, 1);
Atom a4(1, 1, 1);

AtomDyad ad1(a1, a2);
AtomDyad ad2(a3, a4);
AtomDyad ad3(a1, a2); // same as ad1
AtomDyad ad4(a4, a3); // swapped ad3
AtomDyad ad5(a1, a1);
AtomDyad ad6(a1, a1);

uniqueAtomDyad.insert(ad1);
uniqueAtomDyad.insert(ad2);
uniqueAtomDyad.insert(ad3); // not unique
uniqueAtomDyad.insert(ad4); // not unique
uniqueAtomDyad.insert(ad5);
uniqueAtomDyad.insert(ad6); // not unique

assert(uniqueAtomDyad.size() == 3);

您可以通过检查std::set::insert()函数的返回值来检查项目是否已添加到集合中。

相关问题