微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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进行排序.

原文地址:https://www.jb51.cc/c/110548.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐