加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – boost zip_iterator和std :: sort

发布时间:2020-12-16 03:43:43 所属栏目:百科 来源:网络整理
导读:我有两个相同长度的数组值和键. 我想使用keys数组作为键来逐个对值数组进行排序. 我被告知,boost的zip迭代器只是将两个数组锁定在一起并在同一时间向他们做任务的正确工具. 这是我尝试使用boost :: zip_iterator来解决无法使用gcc编译的排序问题.有人可以帮
我有两个相同长度的数组值和键.
我想使用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进行排序.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读