我正在尝试为特定范围生成多个文件(比方说100)的混洗整数(例如:1000,10000等)。这是我到目前为止尝试过的代码
// 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;
}
文件&#39; out.txt&#39;得到覆盖,我最终只有一个文件。如何创建多个文件,每个文件中有不同的混洗整数集?
谢谢
答案 0 :(得分:0)
每次std :: ofstream f2时都使用相同的文件名(&#34; out.txt&#34;);
尝试每次使用不同的名称,例如out1.text,out2.txt,...
你可以在for循环中获得这个表格
std::ostringstream stringStream;
stringStream << "out"<<j<<".txt";
std::string fileName= stringStream.str();
答案 1 :(得分:0)
为了提供一个教育的例子,这可能是我接近它的方式。
评论是内联的。此代码使用了一些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"));
}
}