【问题标题】:C++ Comparing VectorsC++ 比较向量
【发布时间】:2013-02-20 07:25:21
【问题描述】:

我有一个类Table,它有一个成员函数std::vector<Attribute> attributeVec();,其中Attribute 是一个单独的类。

我正在处理想要做某种形式的代码

if (tableA.attributeVec() == tableB.attributeVec()){ ...

其中tableAtableBTable 对象。 我在 Visual Studio 2012 中遇到了很多奇怪的编译器错误,比如

binary '==' : no operator found which takes a left-hand operand of type 'const DatabaseAPI::Attribute' (or there is no acceptable conversion)

所以我相信向量不能像那样进行比较。 如果我可以编译这段代码,我的生活会更轻松,但我该怎么做呢?我可以定义运算符吗?我是否需要重写一些 Attribute 类以便可以比较它们?

细节:编写 API 后,我得到了一组测试,如果合理的话,这些测试需要工作。虽然我相信这至少对我的代码做出了不合理的假设(给定我的 API),但在我的代码中实现它并没有什么坏处。

谢谢!

【问题讨论】:

    标签: c++ vector comparison


    【解决方案1】:

    可以使用== 比较向量,但它们包含的类型(在本例中为Attribute)必须具有比较operator==。如果将其提供给 Attribute 类,则比较应该有效。

    在一个不相关的说明中,他的方法

    std::vector<Attribute> attributeVec();
    

    正在返回一个向量的副本。您必须考虑这是否是您真正想要的行为。

    【讨论】:

      【解决方案2】:

      您需要在 Attribute 类中实现 operator==

      class Attribute {
        bool operator== (const Attribute& other) const {
         // return true if *this == other, otherwise return false
        }
      }
      

      顺便说一句:正如 juanchopanza 所注意到的,您可能只返回来自 attributeVec() 函数的向量的引用,而不是它的副本:

      std::vector<Attribute>& attributeVec();
      

      这样会更有效率,并且在表达式中进行比较(使用operator==):

      o1.attributeVec() == o2.attributeVec()
      

      仍然可以正常工作。

      【讨论】:

      • 也许返回 const 引用的 const 方法更适合这个例子?
      • 嗯,我认为这取决于attributeVec() 的用途。如果客户端代码要修改它,返回非常量引用可能很有用。
      • 可以有两个版本,这里只是比较,不需要也不应该涉及任何非常量操作
      【解决方案3】:

      这个错误基本上是不言自明的,你需要operator== on Attribute

      【讨论】:

        【解决方案4】:

        看看std::equal;第二种形式允许您指定自己的比较函数。

        例子:

        bool compareAttributes (const Attribute &a, const Attribute &b) { /* ... */ }
        
        // assumes attributeVec() returns a reference; if not, then remove '&'
        const std::vector<Attribute>& attribsA = tableA.attributeVec();
        const std::vector<Attribute>& attribsB = tableB.attributeVec();
        
        if(attribsA.size()==attribsB.size() &&
            std::equal(attribsA.begin(), attribsA.end(),
            attribsB.begin(), compareAttributes))
        { /* ... */ }
        

        理想情况下,attributeVec() 返回属性向量的引用。如果你不能这样写,那么attribsAattribsB不应该被定义为引用。 (在这种情况下,您可以考虑为Table 编写一个比较函数,该函数不需要生成Attribute 的向量。)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-04
          • 2015-09-28
          • 2013-08-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多