2013-02-19 81 views
1

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

我与代码,愿做形式

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),但在我的代码中实现这一点并不会有什么坏处。

谢谢!

回答

2

您需要operator==Attribute类实现:

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

BTW:作为juanchopanza注意到,这是可能的,你可能只是一个参考矢量从attributeVec()函数返回,而不是它的一个副本, :

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

这将是更有效和在表达的比较(使用operator==):

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

还可以。

+0

也许一个返回const引用的const方法对于此示例更合适? – juanchopanza 2013-02-19 22:57:56

+0

嗯,我认为这取决于'attributeVec()'的用途。如果客户端代码打算修改它,那么返回非const引用可能很有用。 – piokuc 2013-02-19 22:59:44

+0

你可以有两个版本,但这里只有一个比较,它不需要,也不应该涉及任何非常量操作。 – juanchopanza 2013-02-19 23:00:47

2

可以使用==来比较矢量,但它们的包含类型(本例中为Attribute)必须有比较operator==。如果你将这个分配给Attribute课程,那么比较应该可行。

在一个不相关的音符,他的方法

std::vector<Attribute> attributeVec(); 

返回一个载体的拷贝。你必须考虑这是否是你真正想要的行为。

1

该错误基本上是自解释性的,您需要operator==Attribute

1

看看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不应该被定义为引用。 (在这种情况下,您可能会考虑编写一个不需要生成Attribute向量的Table比较函数。)