C++中的聚类示例

Clustering example in C++

本文关键字:聚类 C++      更新时间:2023-10-16

我有一个这样的增加输入向量{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)

我通常主张不要放弃解决方案,但看起来你陷入了索引和临时向量的泥潭。相反,标准迭代器和算法使这项任务变得轻而易举:

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

在 Coliru 上直播(免费提供蹩脚的输出格式(