C ++带有计时器计时错误。错误与运算符不匹配

问题描述 投票:0回答:1
#include <iostream>
#include <chrono>
#include <unistd.h>
using namespace std;

void SieveOfEratosthenes (int n)
{
    bool prime[n+1], flag=true;
    int counter=0, ct=0;
    for (int i =0;i<n+1;i++){
        prime[i]=true;
    }
    for (int p=2; p*p<=n; p++)
    {
        if (prime[p]==true)
        {
            for (int i=p*2; i<=n; i += p)
            {
                prime[i] = false; 
            }
        }
    }
   // Print all prime numbers 
    for (int p=2; p<=n; p++)
    {
        if (flag)
        {
              auto begin=chrono::high_resolution_clock::now();
        }
        if (prime[p])
        {
              cout << p << " ";
              counter+=1;
              flag=false;
        }
        if(counter==10)
        {
              auto end=chrono::high_resolution_clock::now();
              auto duration=chrono::nanoseconds(end-begin);
              cout<<"Time elapsed:"<<duration.count();
              counter=0;
              flag=true;
        }
    }
    cout<<endl;
}


int main()
{
     int n;
     cout<<"Type a number:";
     cin>>n;
     cout<<endl<<"Following are the prime numbers smaller or equal to:"<<n<<endl;
     SieveOfEratosthenes(n);
     return 0;
}
// Driver Program to test above function 

这是一种算法,用于查找小于n的质数(从键盘给出),我想每找到10个质数就获取时间。我遇到运算符错误,并且它处于(开始)状态。我不知道在哪里错误是。我试图在一个单独的.o文件中编写函数,但仍然一无所获。任何帮助将不胜感激。!

enter image description here

c++ time operator-keyword chrono
1个回答
0
投票

enter image description here是在begin块中定义的,if无法访问。一个简单的解决方法是将定义移出end-begin循环:

for

全局 decltype(chrono::high_resolution_clock::now()) begin; // Print all prime numbers for (int p=2; p<=n; p++) { if (flag) { begin=chrono::high_resolution_clock::now(); } // ... } 通常是个坏主意。由于using namespace stdbegin冲突,因此错误消息变得复杂。如果您改写std::begin,该错误将变得更加清楚:

namespace chrono = std::chrono; using std::cout;
© www.soinside.com 2019 - 2024. All rights reserved.