gpt4 book ai didi

c++ - boost zip 迭代器和 std::sort

转载 作者:可可西里 更新时间:2023-11-01 15:09:18 31 4
gpt4 key购买 nike

我有两个长度相同的数组 valueskeys。我想使用 keys 数组作为键对 values 数组进行按键排序。有人告诉我,boost 的 zip 迭代器是将两个数组锁定在一起并同时对它们执行操作的正确工具。

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

问题出在线路上

std::sort ( boost::make_zip_iterator( keys, values ), boost::make_zip_iterator( keys+N , values+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( ... ))

但这也无法编译,因为 keyskeys+N 的类型不同。我们需要强制 keys 成为一个指针:

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++ - boost zip 迭代器和 std::sort,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9343846/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com