【发布时间】:2012-03-09 18:33:42
【问题描述】:
我有两个长度相同的数组values 和keys。
我想使用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*)’
【问题讨论】:
-
正如 carl-cook 所指出的,最近(重复)question 给出了一个可行的解决方案。另请注意,Eric Niebler 的范围库提供了 just works 的 view::zip。所述库已被提议用于标准化。