【发布时间】:2014-08-11 12:42:38
【问题描述】:
假设我有以下容器:
vector<string> input = assign::list_of("one")("two")("three")("four");
vector<map<string, int> > result;
并说我希望结果看起来像:
{{"one", 1}, {"two", 1}, {"three", 1}, {"four", 1}}
我想使用 STL 算法,我认为 transform 或 for_each 都可以。 对于转换,我有代码:
transform(input.begin(), input.end(), back_inserter(result), boost::bind(assign::map_list_of(_1, 1)));
但这会产生一个编译错误,类似于 no type named 'result_type' in 'class boost::assign_detail::generic_list, int> >'
对于 for_each 我有代码:
for_each(input.begin(), input.end(),
boost::bind<void, void(std::vector<std::map<std::string, int> >::*)(const map<string, int>&)>(
&std::vector<std::map<std::string, int> >::push_back,
&result,
assign::map_list_of(_1, 1)));
但这会产生一个编译错误,总结如下: no match for call to '(boost::_mfi::dm, int>&), std::vector, int> >) (std: :vector, int> >*&, boost::assign_detail::generic_list, int> >&)'
这样做的正确方法是什么?请注意,我不能使用 C++11,我想将 boost_bind 与 STL 算法结合使用,只是为了了解有关 boost::bind 的更多信息。
WRT @Joachim 关于调用 map_list_of 的评论,我做了如下修改:
for_each(input.begin(), input.end(),
boost::bind<void, void(std::vector<std::map<std::string, int> >::*)(const map<string, int>&)>(
&std::vector<std::map<std::string, int> >::push_back,
&result,
boost::bind<void, map<string, int>(const string&, int)>(&assign::map_list_of, _1, 1));
产生编译错误:cannot convert '& boost::assign::map_list_of' (type '') to type 'std::map, int> (*)(const std::basic_string&, int )'
【问题讨论】:
-
顺便说一句,您在
boost::bind调用中使用boost::assign::map_list_of是错误的,因为您实际上调用map_list_of函数,将其结果作为函数传递调用(这当然会给你错误)。
标签: c++ boost boost-bind st