我在比较两个向量中的值时遇到了问题。
以下是我的程序示例代码:
在这个示例代码中,我需要比较两个向量。为此,我使用
因此,我无法使用
作为一种替代方案,我使用了两个向量的迭代器。
并且迭代一个向量并在另一个向量中查找该元素。由于迭代器比较不能使用,因此需要寻找其他方法。
以下是我的程序示例代码:
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()
函数。作为一种替代方案,我使用了两个向量的迭代器。
并且迭代一个向量并在另一个向量中查找该元素。由于迭代器比较不能使用,因此需要寻找其他方法。
operator<
的?问题可能出在这里...我打赌你有一个指针向量,而你的项目按其地址而不是值进行排序。 - J.N.<
和==
运算符? - howard