Sort a vector by even and odd indices. C ++

Is there one linear (or simple without loop) solution for sorting a vector by even and odd indices? Example:

long entries[] = {0,1,2,10,11}; // indices 0 1 2 3 4 std::vector<long> vExample(entries, entries + sizeof(entries) / sizeof(long) ); vExample.sortEvenOdd(vExample.begin(),vExample.end()); // magic one liner I wish existed... for (int i = 0; i < vExample.size(); i++) { std::cout << vExample[i] << " "; } 

Now I would like to have the following output:

 0 2 11 1 10 // corresponding to indices 0 2 4 1 3 
+5
source share
4 answers

I tried to make a real one liner:

  std::stable_partition(std::begin(input), std::end(input), [&input](int const& a){return 0==((&a-&input[0])%2);}); 

And here is the complete program:

 #include <algorithm> #include <iostream> #include <vector> int main() { std::vector<int> input {0,1,2,10,11}; std::stable_partition(std::begin(input), std::end(input), [&input](int const& a){return 0==((&a-&input[0])%2);}); for (auto v : input) std::cout << v << " "; } 

Well, I know, it works only for the reason that the vector uses an adjacent array of elements, and all this is dirty ... But for this there is one liner specified by OP, and it does not require anything superfluous, how to increase ...

+4
source

This is not one liner, but pretty close:

 long entries[] = {0,1,2,10,11}; // indices 0 1 2 3 4 std::vector<long> vExample; for( bool flag : { true, false } ) { auto cond = [&flag]( long ) { flag = !flag; return !flag; }; std::copy_if( std::begin( entries ), std::end( entries ), std::back_inserter( vExample ), cond ); } 
+1
source

If you can use Boost, this will be pretty brief:

 #include <boost/range/adaptor/strided.hpp> #include <boost/range/adaptor/sliced.hpp> #include <boost/range/algorithm_ext/push_back.hpp> #include <iostream> #include <vector> int main() { using namespace boost::adaptors; std::vector<int> input {0,1,2,10,11}; std::vector<int> partitioned; boost::push_back(partitioned, input | strided(2)); boost::push_back(partitioned, input | sliced(1, input.size()) | strided(2)); for (auto v : partitioned) std::cout << v << " "; } 

You can, of course, wrap this in a function to get one liner in the calling code. Live

+1
source

You need stable_partition . Define a predicate that checks if an index is even using modulo 2, and you're good to go.

-1
source

Source: https://habr.com/ru/post/1236257/


All Articles