2012-03-12 94 views
1

我在比较两个向量中的值时遇到了问题。向量迭代器比较

以下是我的程序的示例代码:

template <typename T> bool CompareVectors(std::vector<T> vector1, std::vector<T> vector2) 
    { 
    std::sort(vector1.begin(),vector1.end()); 
    std::sort(vector2.begin(),vector2.end()); 
    if (vector1.size() != vector2.size()) 
     return false; 
    else 
    { 
     bool found = false; 
     std::vector<T>::iterator it; 
     std::vector<T>::iterator it2; 
     for (it = vector1.begin();it != vector1.end(); it++) 
     {  
     for(it2 = vector2.begin(); it2 != vector2.end(); it2++) 
     { 
      if(it == it2) // here i have to check the values in the itearators are equal. 
      { 
      found = true; 
      break; 
      } 
     } 
     if(!found) 
      return false; 
     else 
      found = false; 
     } 
     return true; 
    } 
    }; 

在此示例代码中,我有两个向量进行比较。为此,我使用std::sort()对两个向量进行了排序。由于向量中的数据类型是模板(我在向量中使用类对象),因此std::sort()无法正常工作。也就是说,有时这两个向量在排序后给出不同的元素顺序。

所以我不能使用std::equal()函数也。

对于另一种解决方案,我已经为twi向量使用了两个迭代器。

并迭代一个矢量并在另一个矢量中搜索该元素。为此迭代器比较是不可用的。

+0

你是如何实现'operator <'进行排序的?这可能是你的问题...我敢打赌,你有一个指针向量,你的项目按照他们的地址而不是他们的值进行排序。 – 2012-03-12 04:55:44

+0

您是否为您正在使用的类定义了“<”和“==”运算符? – howardh 2012-03-12 04:56:42

+0

yaa我定义了==,<,!=运算符为我正在使用的类 是的......我在向量中使用poinetr元素进行比较。因此,std :: sorting的问题。所以它是按地址排序的。 – 2012-03-12 05:03:16

回答

2

您第一次使用typename的关键字:

typename std::vector<T>::iterator it; 
typename std::vector<T>::iterator it2; 

没有typename你的代码甚至不会编译。

为了比较通过迭代器指向的,你要做到这一点:

if(*it == *it2) 

你可以写你比较功能:

//changed the name from CompareVectors() to equal() 
template <typename T> 
bool equal(std::vector<T> v1, std::vector<T> v2) 
{ 
    std::sort(v1.begin(),v1.end()); 
    std::sort(v2.begin(),v2.end()); 
    if (v1.size() != v2.size()) 
     return false; 
    return std::equal(v1.begin(),v1.end(), v2.begin()); 
}; 
+1

是的......很好的思考..............非常感谢。 – 2012-03-12 05:15:39

+0

而不是测试大小,然后调用'std :: equal',你可以简单地说'return v1 == v2;' – Blastfurnace 2012-03-12 05:20:29

+0

@Blastfurnace:这很好。我不知道存在'=='非成员函数来测试两个向量的相等性。 – Nawaz 2012-03-12 05:24:05

0

若本线:

if(it == it2) 

if (*it == *it2) 

第一行是比较指针而不是值。

0

这里有很多问题。首先,你说std::sort()不起作用。你是否为你的班级重载operator<

此外,您还需要比较一下迭代器是指向到:

*it == *it2 

此外,你需要通过在同一时间(只有一个循环)两个数组遍历:

for (it = vector1.begin(), it2 = vector2.begin(); 
    it != vector1.end(), it2 != vector2.end(); 
    it++, it2++) { 
    ... 
} 

虽然确实如此,但您应该只是通过重载operator==来使用std::equal()

从效率的角度来看,您应该比较size()之前您打扰排序阵列。