samedi 27 août 2016

How can i compare values of two STD::VECTOR objects with same index

I am new to c++ and trying to understand vectors, my requirement is to compare the values of each index in two vectors.

Below is the pseudocode which works for arrays but not for standard vector class, size of array can be calculated by

mySize = sizeof(array)/sizeof(int);

for(int i = 0;i<mySize;i++)
{
  if(a[i] == b[i])
  {
  std::cout <<": Match ";
  }
  else
  {
   std::cout <<":Doesnt Match" ;
  }

}

but while iam trying to use vectors, it isn't as simple

1.Does Range Based Loops work for the above scenario? 2. How do i get the size of vector , below code is actually showing the extra memory than i have created, probably std::vector vet allocates extra space by default

 std::vector<int> vec;
 vec.push_back( -10 );
 vec.push_back( -20 );
 vec.push_back( -20 );
 vec.push_back( -20 );
 vec.push_back( -20 );
 for (int i=0;i<sizeof(vec);i++)
 {
     std::cout<<vec[i]<<"\t";    
 }

 output :

 10 -20 -20 -20 -20 0   0   0   0   0   0   0   0   0   0   0   0   0      0    0   0   0   0   0

Aucun commentaire:

Enregistrer un commentaire