求素数,用vector存储的实现方法

 更新时间:2020年4月25日 17:46  点击:1692
PS:如有不足之处,还望指正!
复制代码 代码如下:

// tentotwo.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
void GetPrimer(int n, vector<int>& vet)
{
 for (int i = 2; i <= n; i++)
 {
  vet.push_back(i);
 }
 vector<int>::iterator ite = vet.begin();
 while (ite != vet.end())
 {
  vector<int>::iterator tmpite = ite + 1;
  while (tmpite != vet.end())
  {
   if ((*tmpite)%(*ite) == 0)
   {
    tmpite = vet.erase(tmpite);
   }
   else
   {
    tmpite ++;
   }
  }  
  ite ++;
 } 
}
int _tmain(int argc, _TCHAR* argv[])
{
 vector<int> vet;
 GetPrimer(100, vet);
 vector<int>::iterator ite = vet.begin();
 while (ite != vet.end())
 {
  cout << *ite << " ";
  ite ++;
 }
 cout << endl;
 return 0;
}

[!--infotagslink--]

相关文章