Wednesday, September 09, 2009

Compare Vector V1 and V2 for equality

Here are the ways to compare two vectors.

Method 1:



#include < iostream >
using std::cout;
using std::endl;

#include < algorithm >
#include < vector >
#include < iterator >

int main()
{
int a1[ 10 ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int a2[ 10 ] = { 1, 2, 3, 4, 9, 6, 7, 8, 9, 10 };
std::vector<> v1( a1, a1 + 10 );
std::vector<> v2( a1, a1 + 10 );
std::vector<> v3( a2, a2 + 10 );
std::ostream_iterator<> output( cout, " " );

cout << "Vector v1 contains: ";
std::copy( v1.begin(), v1.end(), output );
cout << "\nVector v2 contains: ";
std::copy( v2.begin(), v2.end(), output );
cout << "\nVector v3 contains: ";
std::copy( v3.begin(), v3.end(), output );

// compare vectors v1 and v2 for equality
bool result = std::equal( v1.begin(), v1.end(), v2.begin() );
cout << "\n\nVector v1 " << ( result ? "is" : "is not" ) << " equal to vector v2.\n";
return 0;
}


Method 2:

Overload the == operator for comparision



inline bool operator == (const std::vector< std::string >, const std::vector< std::string >)
{
if (lhs.size() != rhs.size())
return false;

int count = lhs.size();
std::vector< std::string >::const_iterator lhsi = lhs.begin();
std::vector< std::string >::const_iterator rhsi = rhs.begin();
while (count--)
{
if ( *lhsi != *rhsi)
return false;
lhsi++; rhsi++;
}
return true;
}

0 comments:

Post a Comment