为给定的c++范围生成多个混洗整数文件
Generating multiple files of shuffled integers for a given range c++
我正在尝试为特定范围(例如: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();
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何只允许用户输入正整数
- 如何在c++中从文本文件中逐行读取整数
- C++:如何循环通过向量中的整数元素
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 序列化,没有库的整数,得到奇怪的结果
- 在AVX通道中混洗的最佳方式
- 使用具有整数表示和 ULP 的混叠正确比较双精度
- 为给定的c++范围生成多个混洗整数文件
- 如何在设备内存中高效地混洗数据
- c++对动态数组的内容进行混洗