c – boost zip_iterator和std :: sort

我有两个相同长度的数组值和键.
我想使用keys数组作为键来逐个对值数组进行排序.
我被告知,boost的zip迭代器只是将两个数组锁定在一起并在同一时间向他们做任务的正确工具.

这是我尝试使用boost :: zip_iterator来解决无法使用gcc编译的排序问题.有人可以帮我修理这段代码吗?

问题在于这个问题

std :: sort(boost :: make_zip_iterator(keys,values),boost :: make_zip_iterator(键N,值N));

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <algorithm>
#include <boost/iterator/zip_iterator.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_comparison.hpp>



int main(int argc,char *argv[])
{
  int N=10;
  int    keys[N];
  double values[N];
  int M=100;

  //Create the vectors.
  for (int i = 0; i < N; ++i)
   {
     keys[i]   = rand()%M;
     values[i] = 1.0*rand()/RAND_MAX;
   }


  //Now we use the boost zip iterator to zip the two vectors and sort them "simulatneously"
  //I want to sort-by-key the keys and values arrays
   std::sort ( boost::make_zip_iterator( keys,values  ),boost::make_zip_iterator( keys+N,values+N    )
             );
    //The values array and the corresponding keys in ascending order. 
   for (int i = 0; i < N; ++i)
    {
      std::cout << keys[i]   <<  "\t"  << values[i]    << std::endl;  
     }
  return 0;
}

注意:编译时出现错误信息

g++ -g -Wall boost_test.cpp 
boost_test.cpp: In function ‘int main(int,char**)’:
boost_test.cpp:37:56: error: no matching function for call to ‘make_zip_iterator(int [(((unsigned int)(((int)N) + -0x00000000000000001)) + 1)],double [(((unsigned int)(((int)N) + -0x00000000000000001)) + 1)])’
boost_test.cpp:38:64: error: no matching function for call to ‘make_zip_iterator(int*,double*)’

解决方法

您不能排序一对zip_iterators.

首先,make_zip_iterator将一个迭代器的元组作为输入,所以你可以调用

boost::make_zip_iterator(boost::make_tuple( ... ))

但是也不会编译,因为键和键N的类型不相同.我们需要强制键成为一个指针:

std::sort(boost::make_zip_iterator(boost::make_tuple(+keys,+values)),boost::make_zip_iterator(boost::make_tuple(keys+N,values+N)));

这将编译,但是排序的结果仍然是错误的,因为zip_iterator只建立一个Readable iterator,但是std :: sort也需要输入为Writable作为described here,所以你不能使用zip_iterator进行排序.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...