C++ 奇偶数分岔的排序向量

C++ 奇偶数分岔的排序向量,c++,c++11,vector,stl,C++,C++11,Vector,Stl,我试图用sort对一个向量进行排序,这样所有的偶数和奇数都会聚集在一起,但不知怎么的,这似乎不起作用 下面是示例代码 #include <iostream> #include <algorithm> #include <vector> bool myfunction (int i,int j) { return ((i&2)>(j&2)); } bool yourfunction (int i,int j

我试图用sort对一个向量进行排序,这样所有的偶数和奇数都会聚集在一起,但不知怎么的,这似乎不起作用

下面是示例代码

#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;
}
#包括
#包括
#包括
bool-myfunction(inti,intj){return((i&2)>(j&2));}

boolyourfunction(inti,intj){return(i如果您想坚持使用
std::sort
,您可以使用此函数:

bool myfunction (int i,int j) { return ((i % 2) > (j % 2)); }
运行
sort
,输入结果如下:

71
45
53
33 //ODD
32 //EVEN
12
26
80
您可以使用该函数来执行此操作

auto oddStart = std::partition(std::begin(myints),
                               std::end(myints),
                               [](int i){ return i % 2 == 0; });
在此之后,您的偶数值来自

for(auto it = std::begin(myints); it != oddStart; ++it)
可能性很大

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

你回避的原因是什么?我不认为“排序”意味着你认为它的意思。你能发布预期的输出吗?我认为@LightnessRacesinOrbit可能有什么问题。如果我意识到我的错误,我应该使用%运算符