C ++类:从公共函数在for循环中调用私有函数

时间:2019-04-02 04:14:13

标签: c++ class

给出大量的数字

candidates=[6541367000, 6541368000)

发现它们只能由2个质数分解。

我写了一个C ++类,

vector<long long>& prime_fac(N)

返回N个质数的向量,并且

void print2PrimeFactoriation(vector<long long>& candidates)

仅返回具有两个素因数的候选人。

#include <cmath>
#include <iostream>
#include <vector>
using namespace std;

class primeFactorization {
private:
    //vector<long long> prime_vec;
    long long upper_limit;
    vector<long long> res;

    vector<long long>& prime_fac(long long N) {
        vector<long long> prime_vec;
        if (N < 2) {
            cout << "N=" << N << " cannot be factorized by prime numbers" << endl;
        }
        else {
            upper_limit = (long long)sqrt(N);
            while (N%2 == 0) {
                prime_vec.emplace_back(2);
                N /= 2;
            }
            for (long long prime=3; prime<=upper_limit; prime+=2) {
                while (N%prime == 0) {
                    prime_vec.emplace_back(prime);
                }
            }
            prime_vec.emplace_back(N);
        }
        return prime_vec;
    }

public:
    void print2PrimeFactoriation(vector<long long>& candidates) {
        for (long long candidate : candidates) {
            res = prime_fac(candidate);
            cout << candidate << endl;
            if (res.size() == 2) {
                cout << candidate << " can be factorized by 2 prime numbers (";
                cout << res[0] << ", " << res[1] << ")\n";
            }
        }
    }
};


int main() {
    primeFactorization sol;

    vector<long long> candidates;
    for (long long candidate=6541367001; candidate<6541368000; candidate+=2) {
        candidates.emplace_back(candidate);
    }

    sol.print2PrimeFactoriation(candidates);

    return 0;
}

奇怪的是,我收到错误消息:

terminate called after throwing an instance of 'std::bad_alloc'                                                                                                                      
  what():  std::bad_alloc                                                                                                                                                            
Aborted 

我什至试图将候选输入向量简化为仅包含1个元素,但仍然存在相同的错误。

错误是什么?我该怎么做才能解决? 而且,这是进行素分解的最有效方法吗?

1 个答案:

答案 0 :(得分:1)

您正在返回对函数prime_vec中的局部变量vector<long long>& prime_fac(long long N)的引用。

vector<long long>& prime_fac(long long N) {
    vector<long long> prime_vec;
    ...
    ... 
    return prime_vec;
}

此处的局部变量prime_vec的生存期仅限于该函数的范围。退出范围后尝试使用它会导致未定义的行为。

执行此操作时,像GCC and Clang issue a warning这样的编译器:

warning: reference to stack memory associated with local variable 'prime_vec' returned [-Wreturn-stack-address]
        return prime_vec;
               ^~~~~~~~~