mardi 4 août 2015

Sorting vector to bifurcate even and odd numbers

I am trying to sort a vector using sort so that all the even numbers and odd numbers are brought together but somehow that doesnt seem to work.

Sample code below.

#include <iostream>     
#include <algorithm>    
#include <vector>       

bool myfunction (int i,int j) { return ((i&2)>(j&2)); }
bool yourfunction (int i,int j) { return (i<j); }



int main () {
  int myints[] = {32,71,12,45,26,80,53,33};
  std::vector<int> myvector (myints, myints+8);              
  int count=0;
  // using function as comp
  std::sort (myvector.begin(), myvector.end(), myfunction);
    for (std::vector<int>::iterator it=myvector.begin();it!=myvector.end(); ++it)
  std::cout << ' ' << *it;
  std::cout << '\n';
 for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
 {
      if(((*it)&2)==0)
      {
          break;
      }
      count++;
  }
    std::cout << "myvector contains after 1st sort:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
   std::cout << ' ' << *it;
  std::cout << '\n';
  std::sort (myvector.begin()+count, myvector.end(), yourfunction);
    // print out content:
  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
   std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

Aucun commentaire:

Enregistrer un commentaire