不明白为什么我的程序会抛出错误

Can't understand why my program throws error

本文关键字:出错 错误 程序 明白 为什么 我的      更新时间:2023-10-16

我的代码在

#include <iostream>
#include <string>
#include <algorithm>
#include <climits> 
#include <vector>
#include <cmath>
using namespace std;
struct State {
    int v;
    const State *rest;
    void dump() const {
        if(rest) {
            cout << ' ' << v;
            rest->dump();
        } else {
            cout << endl;
        }
    }
    State() : v(0), rest(0) {}
    State(int _v, const State &_rest) : v(_v), rest(&_rest) {}
};
void ss(int *ip, int *end, int target, const State &state) {
    if(target < 0) return; // assuming we don't allow any negatives
    if(ip==end && target==0) {
        state.dump();
        return;
    }
    if(ip==end)
        return;
    { // without the first one
        ss(ip+1, end, target, state);
    }
    { // with the first one
        int first = *ip;
        ss(ip+1, end, target-first, State(first, state));
    }
}
vector<int> get_primes(int N) {
    int size = floor(0.5 * (N - 3)) + 1;
    vector<int> primes;
    primes.push_back(2);
    vector<bool> is_prime(size, true);
    for(long i = 0; i < size; ++i) {
       if(is_prime[i]) {
           int p = (i << 1) + 3;
           primes.push_back(p);
           // sieving from p^2, whose index is 2i^2 + 6i + 3
           for (long j = ((i * i) << 1) + 6 * i + 3; j < size; j += p) {
               is_prime[j] = false;
           }
       }
    }
}
int main() {
    int N;
    cin >> N;
    vector<int> primes = get_primes(N);
    int a[primes.size()];
    for (int i = 0; i < primes.size(); ++i) {
        a[i] = primes[i];
    }
    int * start = &a[0];
    int * end = start + sizeof(a) / sizeof(a[0]);
    ss(start, end, N, State());
}

它接受一个输入 N(整数),并得到所有小于 N 的素数的vector

然后,它从vector中找到唯一集的数量,加起来为 N

get_primes(N)有效,但另一个不起作用。

我借用了其他代码如何找到所有匹配的数字,在给定数组中总和为"N"

请帮助我..我只想要唯一集的数量。

你忘了在get_primes()函数结束时return primes;

我猜问题是:

vector<int> get_primes(int N) {
    // ...
    return primes; // missing this line
}

照原样,你只是在这里写一些垃圾:

vector<int> primes = get_primes(N);

这是未定义的行为 - 在这种情况下表现为崩溃。

相关文章: