【发布时间】:2015-05-07 23:02:04
【问题描述】:
所以基本上我试图用 10^3 个完全随机数“填充”一个文件,所以我可以稍后将它们添加到二进制搜索树中。 这是我目前使用的填充函数:
void populateFile(BinarySearchTree b) {
int random_integer;
srand( time( NULL ) );
std::ofstream myfile;
string line;
myfile.open ("output.txt");
myfile << "Writing this to a file: ";
for(int index=0; index<1000; index++)
{
random_integer = (rand()%1000)+1;
cout << random_integer << endl;
myfile << random_integer;
}
myfile.close();
int value;
ifstream file ("output.txt");
if (file.is_open())
{
while ( getline (file,line) )
{
value = std::stoi(line);
b.insert(value);
}
myfile.close();
}
else cout << "Unable to open file";
}
但我似乎无法写入文件,我只能在控制台上看到数字然后程序崩溃。
我的第二个担心如下: 我想将这些相同的数字添加到二叉搜索树中。我已经有一个类和一个 dd 函数,但我不知道如何继续。然后我希望能够完全随机地从 BST 中删除它们。
我已经编写了一个删除函数。这怎么可能? 任何想法将不胜感激。 P.S:我对 C++ 相当陌生,如果我的问题对你来说听起来很愚蠢,我很抱歉。
【问题讨论】:
-
标题中的问题和帖子中的问题不同。真正的问题是什么?
-
“完全随机” 和
rand类型的冲突。 channel9.msdn.com/Events/GoingNative/2013/… -
问题:你想为一个文件生成 1000 个随机数---但是你将 RNG 范围保持在 1000。为什么不直接在文件中写出 1 到 1000 呢?你想在你的测试数据中重复吗?因为在您当前的生成技术中可能会有多个重复项。
-
@StarPilot 允许重复,我查看了几篇文章,指出这是我可以生成此类数字的方式。所以我实现了自己的功能。谢谢
-
你可能想要
myfile << random_integer << '\n';否则stoi会抛出out_of_range,这可能是导致崩溃的原因。
标签: c++ algorithm sorting binary-tree binary-search-tree