c++ - 将迭代器映射到特定字段上的迭代器(可以使用 Boost)

标签 c++ c++11 boost iterator

假设我有一个适用于一系列整数的特定算法。然后,该函数将在此范围内使用两个迭代器并完成其工作。

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>;

我想在 TupleListSList 上(分别)使用该算法。但是,直接迭代器将不起作用,因为 TupleListSList 不直接包含整数。

一种解决方案是另外向算法传递一个仿函数以解开迭代器:

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/

相关文章:

c++ - 难以理解数组的动态数组的一种实现

C++ 内存缓存库

c++ - 使用 new 放置移动构造对象

c++ - 你知道在 C++ 中获取线程本地存储的不同方法的一些性能测试吗?

c++ - 如何正确设置标志

c++ - Boost的Dijkstra算法教程

c++ - 使用 Unix 域套接字 (UDS) 替代 splice(2)

c++ - 当短路禁用其评估时,正在读取常量表达式中允许的尾数指针

c++ - 是否可以在 boost::test 上使用自动注册的 BOOST_PARAM_TEST_CASE?

c++ - boost::typeindex::type_id<T>().pretty_name() 不是 "pretty"