C ++中的聚类示例

时间:2018-01-31 03:16:54

标签: c++ vector

我有一个增加输入向量,就像这个{0, 1, 3, 5, 6, 7, 9}一样,想要像这样{{0, 1}, {3}, {5, 6, 7}, {9}}聚类输入,即只聚类作为邻居的整数。数据结构std::vector<std::vector<int>> solution(const std::vector<int>& input)

1 个答案:

答案 0 :(得分:1)

我通常主张不提供解决方案,但看起来你陷入了索引和临时载体的困境。相反,标准迭代器和算法使这项任务变得轻而易举:

std::vector<std::vector<int>> solution(std::vector<int> const &input) {
    std::vector<std::vector<int>> clusters;

    // Special-casing to avoid returning {{}} in case of an empty input
    if(input.empty())
        return clusters;

    // Loop-and-a-half, no condition here
    for(auto it = begin(input);;) {
        // Find the last element of the current cluster
        auto const last = std::adjacent_find(
            it, end(input),
            [](int a, int b) { return b - a > 1; }
        );

        if(last == end(input)) {
            // We reached the end: register the last cluster and return
            clusters.emplace_back(it, last);
            return clusters;
        }

        // One past the end of the current cluster
        auto const gap = next(last);

        // Register the cluster
        clusters.emplace_back(it, gap);

        // One past the end of a cluster is the beginning of the next one
        it = gap;
    }
}

See it live on Coliru (免费输出格式错误)