c – 获取std :: vector>中所有T的视图

想象一下,我有一个类似于std :: vector< std :: tuple< Ts ...>>的容器.

从那以后,我想对所有T进行“查看”(非复制),这样我就可以对该视图进行操作,就好像它是一个类似标准的容器一样.

那么我想要的是:

using tuple_vector = std::vector<std::tuple<int,float,double>>;
tuple_vector tuple_vec = {{1, 4.f, 8.},
                          {2, 5.f, 9.},
                          {3, 6.f, 10.},
                          {4, 7.f, 11.}}

auto int_view = view<int>(tuple_vec);
^^^
type should be some kind of non-owning reference 

// what I would like to do
int_view[0] = 10; // modify
assert(int_view[0] == std::get<int>(tuple_vec[0])); // modification should modify tuple_vec as well

我尝试过std :: transform,但后来我得到了所有int的拥有副本.

std::vector<int> int_vec(tuple_vec.size());
std::transform(tuple_vec.begin(), tuple_vec.end(), int_vec.begin(), [&](const auto& elem) {
    return std::get<int>(elem);
});

我不确定这是否可行,但如果是这样,我会很感激任何提示或方向.

解决方法:

你可以创建一个std::reference_wrapper的向量:

template <typename T, typename ContainerOfTuples>
auto make_refs_to(ContainerOfTuples& tuples) {
    using RefType = std::reference_wrapper<T>;

    std::vector<RefType> refs;
    refs.reserve(std::size(tuples));
    std::transform(std::begin(tuples), std::end(tuples), std::back_inserter(refs),
                   [](auto& tup) -> RefType { return {std::get<T>(tup)}; });
    return refs;
}

auto double_view = make_refs_to<double>(tuple_vec);
double_view[1].get() += 3.14;  // Caveat: must access through .get().

Live Example

更进一步……这是我们如何获得许多类型的引用:

namespace detail {

// When many types are asked for, return a tuple of references.
template <typename... T> struct RefTypeImpl {
    using type = std::tuple<std::reference_wrapper<T>...>;
};

// When a single type is asked for, return a single reference.
template <typename T> struct RefTypeImpl<T> {
    using type = std::reference_wrapper<T>;
};

// When two types are asked for, return a pair for more convenient access.
template <typename T, typename U> struct RefTypeImpl<T, U> {
    using type = std::pair<std::reference_wrapper<T>, std::reference_wrapper<U>>;
};

}  // namespace detail

template <typename... Ts, typename ContainerOfTuples>
auto make_refs_to(ContainerOfTuples& tuples) {
    using RefType = typename detail::RefTypeImpl<Ts...>::type;

    std::vector<RefType> refs;
    refs.reserve(std::size(tuples));
    std::transform(std::begin(tuples), std::end(tuples), std::back_inserter(refs),
                   [](auto& tup) -> RefType { return {std::get<Ts>(tup)...}; });
    return refs;
}

auto int_float_view = make_refs_to<int, float>(tuple_vec);
std::cout << (int_float_view[2].first.get() == 3) << '\n';

Live Example

上一篇:python – 比较两个元组列表


下一篇:在java中对元组列表进行排序的有效方法