2016-10-27 13 views
2

素数をファイルに書き込むためにコードを書きます。その後、多くのスレッドで作業を分けるために別の関数を書きます。しかし、私の問題は、コンパイラはエラーにofstream:ofstreamに変換できません&

 
error C2664: 'void (int,int,std::ofstream &)' : cannot convert argument 3 from 
'std::basic_string,std::allocator>' to 'std::ofstream &'. 

私を書きですが、私の問題は、私はエラーが言うことを理解していないと私は禁止されていることを行う場所ということです。

これは私のコードです:

void writePrimesToFile(int begin, int end, ofstream& file) 
{ 
    int i, j, prime = 1; 

    for (i = begin; i <= end; i++) { 
     for (j = begin; i <= end/2; j++) { 
      if (i % j == 0) { 
       prime = 0; 
      } else { 
       file << i << endl; 
      } 
     } 
    } 
} 

void callWritePrimesMultipleThreads(int begin, int end, string filePath, int N) 
{ 
    double startTimer, stopTimer; 

    startTimer = clock(); 
    thread* arr = new thread[N]; 
    for (int i = 0; i < N; i++) { 
     int start = begin; 
     int finish = N; 
     arr[i] = thread(writePrimesToFile, start, finish, ref(filePath)); 
     start = finish; 
     finish += N; 
    } 
    for (int i = 0; i < N; i++) { 
     arr[i].join(); 
    } 
    stopTimer = clock(); 
    cout << "The time that takes is: " << 
      double(stopTimer - startTimer)/CLOCKS_PER_SEC << endl; 
} 
+2

あなたは 'のstdを望んでいるあなたのスレッド関数に'のstd :: STRING'オブジェクトへの参照を渡している:: ofstream'参照を(明確に述べ:簡単にし、代わりにstd::vector<std::thread>を使用してきれいになりますメッセージに)。それはうまく動作しません。 –

+0

ああ、あなたにはメモリリークがあります。代わりに 'std :: vector'を使わないのはなぜですか? –

+0

@Someprogrammerdudeどこでメモリリークがありますか?もっと説明できますか? –

答えて

4

あなたのスレッド機能を使用すると、代わりにstd::stringへの参照をバインドしようとしている、std::ofstream参考として三番目のパラメータを期待しています。だから、ループの前にstd::ofstreamを作成し、それを渡します。

void callWritePrimesMultipleThreads(int begin, int end, string filePath, int N) 
{ 
    double startTimer, stopTimer; 

    std::ofstream file(filePath); 
    // check that file is opened 

    startTimer = clock(); 
    ... 
     arr[i] = thread(writePrimesToFile, start, finish, ref(file)); 

あなたが動的にnew[]によって糸の配列を割り当て、したがって、あなたの関数の終了メモリリークでdelete[]を持っていません。

//thread* arr = new thread[N]; 
std::vector<std::thread> arr(N); // replace with this and you do not need to touch anything else 
+0

なぜベクトルで私は自由のようなメモリをきれいにする必要はありませんか削除? –

+0

@RonyCohen 'std :: vector'のインスタンスはあなたの関数の範囲で自動的に変数になるので、そのデストラクタはリソースベクタを整理します。 – Slava

+0

ごめんなさい申し訳ありません –

関連する問題