我正在尝试使用排序对矢量进行排序,以便将所有偶数和奇数组合在一起但不知何故似乎不起作用.
示例代码如下.
#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;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用该功能std::partition执行此操作.
auto oddStart = std::partition(std::begin(myints),
std::end(myints),
[](int i){ return i % 2 == 0; });
Run Code Online (Sandbox Code Playgroud)
在此之后你的偶数值来自
for(auto it = std::begin(myints); it != oddStart; ++it)
Run Code Online (Sandbox Code Playgroud)
而赔率是
for(auto it = oddStart; it != std::end(myints); ++it)
Run Code Online (Sandbox Code Playgroud)