在C+中,有没有一种方法可以将向量从一个辅助函数传递到另一个辅助函数+;? 我正在通过一个经典的C++练习来编写一个程序来确定哪些数字是素数。我现在正在处理的版本要求我能够确定哪些值是由名为max的用户输入的一个值的素数

在C+中,有没有一种方法可以将向量从一个辅助函数传递到另一个辅助函数+;? 我正在通过一个经典的C++练习来编写一个程序来确定哪些数字是素数。我现在正在处理的版本要求我能够确定哪些值是由名为max的用户输入的一个值的素数,c++,vector,C++,Vector,我试图构造的算法的行为方式如下: 1) 输入所需的max值 2) 取此max,然后将其放入一个函数中,该函数将计算sqrt(max) 3) 使用sqrt(max)我将构造一个素数向量,其值为sqrt(max) 4) 使用此sqrt(max)向量,我将通过创建一个特定函数来确定列表中截至max的哪些值为素数,从而评估哪些值为该值的素数。然后我将生成所有这些素数的列表 这是我的努力代码: #包括“pch.h” #包括 #包括 #包括 #包括 #包括 使用std::cin; 使用std::cout;

我试图构造的算法的行为方式如下:

1) 输入所需的
max

2) 取此
max
,然后将其放入一个函数中,该函数将计算
sqrt(max)

3) 使用
sqrt(max)
我将构造一个素数向量,其值为
sqrt(max)

4) 使用此
sqrt(max)
向量,我将通过创建一个特定函数来确定列表中截至
max
的哪些值为素数,从而评估哪些值为该值的素数。然后我将生成所有这些素数的列表

这是我的努力代码:

#包括“pch.h”
#包括
#包括
#包括
#包括
#包括
使用std::cin;
使用std::cout;
使用std::string;
使用std::vector;
整数确定素数(整数x){
//用于确定一个数是否为素数的函数
//使用了这样一个事实:要确定数字是否为素数,只需检查
//小于sqrt(x)的素数值除以x
素数的向量=素数的列表();
vp_1=x%vp_1=x%sqrt_素数的向量_[i];
对于(inti=0;icout下面是解决问题的两种不同方法。一种方法返回向量,另一种方法使用pass by reference来修改传递到参数中的向量

#include <iostream>
#include <vector>
#include <string>

bool is_prime(int number){

    //exceptions
    if(number == 1) return false;
    if(number == 2 || number == 5) return true;

    std::string str = std::to_string(number);
    if(str.back() == '1' || str.back() == '3' || str.back() == '7' ||  str.back() == '9'){
        for(int i = 3; i * i <= number; i++){
            if(number % i == 0){
                return false;
            } 
        }
        return true;
    }
    return false;
}

//adds the value to the vector passed in and the values will 'save'
void find_primes(std::vector<int>& primes, int max){

    for(int i = 0; i < max; i++){
        if(is_prime(i)) primes.push_back(i);
    }
}

//adds the results to a vector and returns that vector
std::vector<int> return_vec_primes(int max){

    std::vector<int> results;
    for(int i = 0; i < max; i++){
        if(is_prime(i)) results.push_back(i);
    }

    return results;
}

int main(){

    std::vector<int> reference_vec;

    //pass the vector into the function
    find_primes(reference_vec, 100);

    //the function will return the vector into 'returned_vec'
    std::vector<int> returned_vec = return_vec_primes(100);

    //same results
    for(int i : reference_vec) std::cout << "prime: " << i << "\n";
    for(int i : returned_vec) std::cout << "prime: " << i << "\n";

    return 0;
}
#包括
#包括
#包括
布尔是素数(整数){
//例外情况
如果(number==1)返回false;
if(number==2 | | number==5)返回true;
std::string str=std::to_字符串(数字);
如果(str.back()=“1”| | str.back()=“3”| | str.back()=“7”| | str.back()=“9”){

对于(int i=3;i*i)返回向量或使用传递引用如何?我将如何返回向量?它是否像我在上面输入的返回命令一样简单?还不确定传递引用。但是返回向量听起来对我来说是合法的。