【发布时间】:2012-03-28 13:09:19
【问题描述】:
比较两个向量中的值时遇到问题。
以下是我的程序的示例代码:
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<的排序的?这可能是你的问题......我敢打赌你有一个指针向量,并且你的项目按它们的地址而不是它们的值排序。 -
您是否为正在使用的类定义了
<和==运算符? -
yaa 我已经为我正在使用的类定义了==、
标签: c++ vector iterator comparison