我在比较两个向量中的值时遇到了问题。向量迭代器比较
以下是我的程序的示例代码:
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向量使用了两个迭代器。
并迭代一个矢量并在另一个矢量中搜索该元素。为此迭代器比较是不可用的。
你是如何实现'operator <'进行排序的?这可能是你的问题...我敢打赌,你有一个指针向量,你的项目按照他们的地址而不是他们的值进行排序。 – 2012-03-12 04:55:44
您是否为您正在使用的类定义了“<”和“==”运算符? – howardh 2012-03-12 04:56:42
yaa我定义了==,<,!=运算符为我正在使用的类 是的......我在向量中使用poinetr元素进行比较。因此,std :: sorting的问题。所以它是按地址排序的。 – 2012-03-12 05:03:16