Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 以某种方式用素数填充向量_C++_Vector_Primes - Fatal编程技术网

C++ 以某种方式用素数填充向量

C++ 以某种方式用素数填充向量,c++,vector,primes,C++,Vector,Primes,我被要求用素数填充给定的向量,我不能使用任何其他向量、数组或集合。我想出了这样的办法,但它不能正常工作,我也不知道为什么 #include <iostream> #include <vector> #include <algorithm> using namespace std; bool isPrime(int n){ if (n<=1){return false;} for (

我被要求用素数填充给定的向量,我不能使用任何其他向量、数组或集合。我想出了这样的办法,但它不能正常工作,我也不知道为什么

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool isPrime(int n){                           
    if (n<=1){return false;}
    for (int i = 2; i < n; i++){
        if (n % i == 0){
            return false;
        }
    }
    return true;}

int fillWithPrimesVec(vector<int>& vec){
    for (int i = 0; i < vec.size(); i++){
        for (int j = 0; j<INT_MAX; j++){
            if (isPrime(j)){
                vec.push_back(j);}
            else{continue;}
            }
        }

    return vec[0];
}

int main(){

int c[15];
size_t szc = sizeof(c)/sizeof(*c);
vector<int> d(szc,0);

cout << fillWithPrimesVec(d);

return 0;
}
#包括
#包括
#包括
使用名称空间std;
bool isPrime(int n){

如果(n不久前有人用代码发表了评论,但我再也找不到了。 我对代码做了一些修改,它似乎可以工作。只是它填充了16个数字,而不是15个

`
#include "stdafx.h"
#include <iostream>

#include <vector>
#include <climits>


bool isPrime(int n)
{
    if (n <= 1) { return false; }
    for (int i = 2; i < n / 2; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

int fillWithPrimesVec(std::vector<int> &vec, const size_t size)
{
    for (int j = 0; j < INT_MAX && vec.size() <= size; j++) {
        if (isPrime(j)) {
            vec.push_back(j);
        }
    }
    for (int j = 0; j < INT_MAX && vec.size() <= size; j++)
    return vec[j];
}

    int main()
    {
        std::vector<int> d;
        fillWithPrimesVec(d, 15);
        for (auto item : d)
            std::cout << item << " ";
        return 0;
    }
`
`
#包括“stdafx.h”
#包括
#包括
#包括
bool isPrime(int n)
{

if(n)看起来像一个基本的调试场景。它肯定是在你告诉它的地方放置素数。1.你被告知用素数填充向量的方法是什么?2.向量当前是如何用素数填充的?没有指定的方法用素数填充向量,这就是我想到的。我认为vec.push_back()用给定的参数填充向量,我错了吗?那些需要是提升的素数。我不喜欢C++,这就是我的问题来自的。“没有指定的方式用向量填充向量”抱歉我不清楚。我的意思是,“当你完成时,向量中必须有什么素数的模式。”你的原点。“我被告知用素数填充向量”可能只是你一遍又一遍地用数字3填充它。感谢你的澄清,请将其添加到你的问题正文中。你首先调整向量的大小,然后再将其推回。这可能不是你想要做的。
for(int j=0;j