获取表示地图子集的向量

Getting vectors representing subsets of a map

我想根据固有顺序获取表示地图连续元素的特定长度的每个可能子集的向量,例如:

如何做到这一点?

您可以在映射中迭代,因为键是有序的:

std::vector<std::array<Sample, 3u>> get_triplets(const std::map<int, Sample>& samples)
{
    if (samples.size() < 3) {
        return {};
    }
    std::vector<std::array<Sample, 3u>> res;

    auto it = samples.begin();
    auto it1 = std::next(it);
    auto it2 = std::next(it1);

    for (; it2 != samples.end(); ++it, ++it1, ++it2) {
        res.push_back({{it->second, it1->second, it2->second}});
    }
    return res;
}

Live Demo

编辑:有 n-uplets,与以前的三联体版本相比有小的变化:

std::vector<std::vector<Sample>> get_n_uplets(std::size_t n, const std::map<int, Sample>& samples)
{
    if (samples.size() < n) {
        return {};
    }
    std::vector<std::vector<Sample>> res;

    auto first = samples.begin();
    auto last = std::next(first, n - 1);

    for (; last != samples.end(); ++first, ++last) {
        std::vector<Sample> inner;

        for (auto it = first; it != std::next(last); ++it) {
            inner.push_back(it->second);
        }
        res.push_back(inner);
    }
    return res;
}

Live Demo