假设我有一个适用于一系列整数的特定算法。然后,该函数将在此范围内使用两个迭代器并完成其工作。
template <typename It>
void doWork(It begin, It end) {
int x = *begin; // range is over integers
// ...
}
假设我有两个数据结构:
struct S { int x; }
using TupleList = std::vector<std::tuple<int, double>>;
using SList = std::vector<S>;
我想在 TupleList
和 SList
上(分别)使用该算法。但是,直接迭代器将不起作用,因为 TupleList
和 SList
不直接包含整数。
一种解决方案是另外向算法传递一个仿函数以解开迭代器:
template <typename It, typename Unwrap>
void doWork(It begin, It end, Unwrap unwrap) {
int x = unwrap(*begin);
// And so on
}
// -----
auto Sunwrapper = [](const S& s) { return s.x; }
doWork(begin(Slist), end(Slist), Sunwrapper);
但我更愿意保持函数整洁。 C++(加上 Boost)有没有办法从这样的解包函数自动创建迭代器?
auto unwrappedBegin = some_magical_factory(begin(Slist), Sunwrapper);
auto unwrappedEnd = some_magical_factory(end (Slist), Sunwrapper);
doWork(unwrappedBegin, unwrappedEnd);
最佳答案
boost::transform_iterator
似乎是一个合适的适配器。只需将 some_magical_factory
替换为 boost::make_transform_iterator
,包含适当的 header ,它就应该可以工作。
关于c++ - 将迭代器映射到特定字段上的迭代器(可以使用 Boost),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41441940/