简体   繁体   中英

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;
}

You can use the function std::partition to do this.

auto oddStart = std::partition(std::begin(myints),
                               std::end(myints),
                               [](int i){ return i % 2 == 0; });

After this your even values are from

for(auto it = std::begin(myints); it != oddStart; ++it)

and the odds are

for(auto it = oddStart; it != std::end(myints); ++it)

If you want to stick to using std::sort you can use this function:

bool myfunction (int i,int j) { return ((i % 2) > (j % 2)); }

Running sort with your input results in:

71
45
53
33 //ODD
32 //EVEN
12
26
80

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM