如何用随机数填充文件?

abe*_*out 4 c++ sorting algorithm binary-tree binary-search-tree

所以基本上我试图用 10^3 个完全随机数“填充”一个文件,所以我可以稍后将它们添加到二叉搜索树中。这是我目前使用的 populate 函数:

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";

}
Run Code Online (Sandbox Code Playgroud)

但是我似乎无法写入文件,我只能在控制台上看到数字然后程序崩溃。

我的第二个问题如下:我想将这些相同的数字添加到二叉搜索树中。我已经有一个类和一个 dd 函数,但我不知道如何继续。然后我希望能够完全随机地从 BST 中删除它们。

我已经写了一个删除函数。这怎么可能?任何想法将不胜感激。PS:我对 C++ 相当陌生,如果我的问题对你来说很愚蠢,我很抱歉。

R S*_*ahu 5

我认为您的问题的解决方案在于@Praetorian 的评论:

你可能想要myfile << random_integer << '\n';. 否则stoi会 throw out_of_range,这可能是导致崩溃的原因。

我有一些关于您的功能的通用建议。

  1. 将您的功能一分为二

    -- 一个用于写入文件
    -- 一个用于从文件中读取并填充 BST。

  2. 不要在函数中使用硬编码的文件名或全局变量。使它们成为函数的参数。

  3. 始终检查 IO 操作的状态。处理失败。

  4. 将随机数生成器植入main或驱动程序函数中。如果多次调用生成随机数的函数,则无需再次为随机生成器设置种子。

void populateFile(int count,
                  std::string const& file)
{
    std::ofstream myfile(file);
    if (!myfile )
    {
       // Deal with error.
       return;
    }

    for(int index=0; index<count; index++)
    {
        random_integer = (rand()%1000)+1;
        myfile << random_integer << "\n";
    }
}

void readFileAndBuildBST(std::string const& file,
                         BinarySearchTree& b)
{
    std::ifstream myfile(file);
    if (!myfile )
    {
       // Deal with error.
       return;
    }

    int number;
    while ( myfile >> number )
    {
       b.insert(number);
    }
}

void driver()
{
   // Seed the random number generator.
   srand( time( NULL ) );

   // Populate the file
   std::string file("output.txt");
   populateFile(1000, file);

   // Read the data from the file and flesh out the BST.
   BinarySearchTree b;
   readFileAndBuildBST(file, b);
}
Run Code Online (Sandbox Code Playgroud)

将功能一分为二,您可以一次测试一个功能。如果一个函数存在问题,您可以先调试问题并修复它,然后再处理另一个函数。