按偶数和奇数索引对向量进行排序。 C++

Sort vector by even and odd indices. c++

是否有单行(或简单的无循环)解决方案来按偶数和奇数索引对向量进行排序? 示例:

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

现在我想要以下输出:

0 2 11 1 10 // corresponding to indices 0 2 4 1 3

您需要的是stable_partition。定义一个谓词来检查索引是否甚至使用模 2,你就可以开始了。

这不是一个班轮,但非常接近:

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

如果你可以使用Boost,这就相当简洁了:

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

您当然可以将其包装在一个函数中,以便在调用代码中获得一个单行代码。 Live

我试着做了一个真正的 one liner:

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

这是完整的程序:

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

好的,我知道,它起作用的唯一原因是 vector 使用了一个连续的项目数组,而且整个东西都很脏……但这是 OP 要求的一个衬里,它不需要任何东西额外喜欢 boost...

我不喜欢摆弄@fjardon 接受的答案所建议的地址的麻烦事。 @Slava 的建议要好得多,并结合 OP 的代码给出了一些效果很好的东西:

int main() {
   std::vector<int> vals {0,2,3,-3,8,-5,7,8};
  bool flag = true;
    std::stable_partition(begin(vals), end(vals), [&flag] (auto el) mutable
                          {
                            // toggle flag, return previous value
                            flag = !flag; return !flag;
                          });
    for (auto v : vals)
        std::cout << v << " ";
} 

Output: 0 3 8 7 2 -3 -5 8