I have a problem while comparing the values in two vectors.
Following is the sample code of my program:
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;
}
};
In this sample code I have to compare the two vectors. For that I have sorted the two vectors using std::sort(). Since the data type in the vector is a template (I am using a class object in the vector), the std::sort() is not working properly. Ie, sometimes the two vectors give different order of elements after sorting.
So I am not able to use the std::equal() function also.
For an alternative solution, I have used two iterators for the twi vectors.
And iterating one vector and searches that element in the other vector. For this the iterator comparison is cannot be usable.
First you’ve to use
typenamekeyword here:without
typenameyour code wouldn’t even compile.To compare the values pointed to by iterators, you’ve to do this:
You could write you compare function as: