为给定的c++范围生成多个混洗整数文件

Generating multiple files of shuffled integers for a given range c++

本文关键字:混洗 整数 文件 c++ 范围      更新时间:2023-10-16

我正在尝试为特定范围(例如:1000、10000等)生成多个混洗整数文件(比如100)。这是我迄今为止尝试过的代码

// random_shuffle example
#include <iostream>     // std::cout
#include <algorithm>    // std::random_shuffle
#include <vector>       // std::vector
#include <ctime>        // std::time
#include <cstdlib>      // std::rand, std::srand
#include <fstream>
// random generator function:
int myrandom (int i) { return std::rand()%i;}
int main(){
   std::srand ( unsigned ( std::time(0) ) );
   std::vector<int> myvector2;
// For creating 10 different shuffled files
   for(int j=0;j<10;j++){
// set some values:
      for (int i=1; i<=10000; ++i) myvector2.push_back(i);
// using built-in random generator:
      std::random_shuffle ( myvector2.begin(), myvector2.end() );
// using myrandom:
      std::random_shuffle ( myvector2.begin(), myvector2.end(), myrandom);
// print out content:
       std::cout << "Data Shuffled:";
// put content in out file
      std::ofstream f2("out.txt");
       for (std::vector<int>::iterator it=myvector2.begin(); it!=myvector2.end(); ++it)
       f2<< *it <<'n';
     }
return 0;
}

文件"out.txt"被覆盖,我只得到一个文件。如何创建多个文件,每个文件中都有不同的混洗整数集?

谢谢

为了提供一个教育示例,我可能会这样做。

注释是内联的。此代码使用了一些c++14特性。

请注意,整个操作是用标准算法表示的。这是使代码可移植、可维护、正确的最佳方式,并为编译器提供最佳的优化机会。

#include<random>
#include<fstream>
#include<vector>
#include<utility>
#include<iterator>
#include<algorithm>
// generate a vector of all integers in the set Is...
template<int...Is>
auto initial_vector(std::integer_sequence<int, Is...>)
{
    return std::vector<int>({ Is... });
}
// defering to template expansion function allows the compiler to populate the vector from a compile-time
// computed data table. Totally unnecessary, but I find it pleasing.
auto initial_vector()
{
    return initial_vector(std::make_integer_sequence<int, 10000>());
}
int main()
{
    auto eng = std::default_random_engine(std::random_device{}());
    // make our initial vector
    auto data = initial_vector();
    // for each data set...
    for (int i = 0 ; i < 100 ; ++i)
    {
        // shuffe the data...
        std::shuffle(std::begin(data), std::end(data), eng);
        // create a filename from th index of the data set
        auto strm = std::ofstream("data" + std::to_string(i) + ".txt");
        // copy the data-set to the file, encoded as newline-delimited strings representing decimal integers
        std::copy(std::begin(data), std::end(data), std::ostream_iterator<int>(strm, "n"));
    }
}

每次std::ofstream f2("out.txt")时都使用相同的文件名;

尝试在每次使用不同的名称,例如out1.text、out2.txt、…

你可以在for循环中得到这个表格j

std::ostringstream stringStream;
stringStream << "out"<<j<<".txt";
std::string fileName= stringStream.str();