下面的代碼編譯失敗對我來說:從live example的std :: for_each的用的boost :: zip_iterator編譯失敗
#include <iostream>
#include <vector>
#include <boost/iterator/zip_iterator.hpp>
typedef boost::tuple<int&, float&> EntryTuple;
struct zip_func :
public std::unary_function<EntryTuple&, void>
{
void operator()(EntryTuple& t) const
{
std::cout << t.get<0>() << " " << t.get<1>() << std::endl;
}
};
int main()
{
const int N = 5;
std::vector<int> intVec(N,2);
std::vector<float> valueVec(N,5.5);
std::for_each(
boost::make_zip_iterator(
boost::make_tuple(intVec.begin(), valueVec.begin())
),
boost::make_zip_iterator(
boost::make_tuple(intVec.end(), valueVec.end())
),
zip_func()
);
return 0;
}
錯誤消息:
In file included from /usr/include/c++/4.9/algorithm:62:0, from /usr/include/boost/utility/swap.hpp:24, from /usr/include/boost/tuple/detail/tuple_basic.hpp:40, from /usr/include/boost/tuple/tuple.hpp:33, from /usr/include/boost/iterator/zip_iterator.hpp:19, from prog.cpp:4: /usr/include/c++/4.9/bits/stl_algo.h: In instantiation of '_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = boost::zip_iterator >, __gnu_cxx::__normal_iterator >, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type> >; _Funct = zip_func]': prog.cpp:34:1:
required from here /usr/include/c++/4.9/bits/stl_algo.h:3755:14: error: no match for call to '(zip_func) (boost::iterator_facade >, __gnu_cxx::__normal_iterator >, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type> >, boost::tuples::cons >, boost::random_access_traversal_tag, boost::tuples::cons >, int>::reference)' __f(*__first); ^prog.cpp:9:8: note: candidate is: struct zip_func : ^prog.cpp:12:8: note: void zip_func::operator()(EntryTuple&) const void operator()(EntryTuple& t) const ^prog.cpp:12:8: note: no known conversion for argument 1 from 'boost::iterator_facade >, __gnu_cxx::__normal_iterator >, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type> >, boost::tuples::cons >, boost::random_access_traversal_tag, boost::tuples::cons >, int>::reference {aka boost::tuples::cons >}' to 'EntryTuple& {aka boost::tuples::tuple&}'
如果我加入一些const
S,它compiles:
typedef boost::tuple<const int&, const float&> EntryTuple;
struct zip_func :
public std::unary_function<const EntryTuple&, void>
{
void operator()(const EntryTuple& t) const
{
std::cout << t.get<0>() << " " << t.get<1>() << std::endl;
}
};
是什麼原因?
Boost的拉鍊迭代器是一個僅供查看的迭代器?順便說一句,'std :: unary_function'是你的C++ 03。 – Yakk