减去连续的集合元素

subtract consecutive set elements

我正在尝试实现 solLoops 函数的集合版本:

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <ctime>
#include <vector>
#include <algorithm>
#include <unordered_set>

int solLoops(std::vector<int> A)
{

    int count = 0;
    for (int i = 0; i < A.size() - 1; ++i)
    {
        if (A[i + 1] - A[i] <= 1)
        {
            count++;
        }
    }
    return count;
}

int solSet(std::vector<int> A)
{
    std::unordered_set<int> S;

    for (int i = 0; i  < A.size(); ++i)
    {
        S.insert(A[i]);
    }

    int count = 0;
    for (auto it = S.begin(); it != std::prev(S.end()); ++it)
    {
        auto it2 = std::next(it, 1);
        if (*it2 - *it <= 1)
        {   
            count++;
        }
    }

    return count;
}



int main() {

    const unsigned int N = 4;

    std::vector<int> A;
    A.reserve(N);
    A.emplace_back(11);
    A.emplace_back(12);
    A.emplace_back(13);
    A.emplace_back(1);
    A.emplace_back(2);

    //int result = solLoops(A);
    int result = solSet(A);
    std::cout << "Result is: " << result << "\n";
    std::cout << "\n";

    return 0;
}

但是我遇到了段错误。 我正在尝试实现循环:

for (int i = 0; i < A.size() - 1; ++i)

来自

for (auto it = S.begin(); it != std::prev(S.end()); ++it)

并做减法:

if (A[i + 1] - A[i] <= 1)

作为

auto it2 = std::next(it, 1); if (*it2 - *it <= 1)

(我知道集合包含随机顺序的元素。我只是想弄清楚如何在这里做减法)

std::unordered_set have forward iterators (which can only go forward). But std::prev requires a bidirectional iterator.

您可以通过检查 next 迭代器是否结束来解决您的问题:std::next(it) != S.end()。或者改用 std::set,其中 个双向迭代器。