写入文件时,矢量下标超出范围

vector subscript out of range when writing to file

本文关键字:下标 范围 文件      更新时间:2023-10-16

我想写一个向量到一个文件,它表示一个函数的结果,该函数以"double Golf_dl"的步长增加j。vector本身必须包含"int Golf_NL"元素。(Golf_dl是类Tsunami的私有成员)问题是我得到一个所有值都等于0.5的常量向量,这是垃圾。有人能看出哪里不对吗?

代码:

void T_Tsunami::Toestand(int nl)
{
    struct pb
    {
        std::vector<double>& v_;  
        pb(std::vector<double>& v) 
        : v_(v){}; 
        pb& operator+(double i) 
        {
            v_.push_back(i);
            return *this;  
        }
    };
    for( double i = 0; i < nl; i++ )
    {   
        double j=0; 
        double y = 0.25*(1-tanh(double(j-75)/5));
        j+=Golf_dl;
        pb(T_1)+y; 
    }
}
void T_Tsunami::Write(vector<double>d)
{
        const int Naamgrootte=64; 
        char Naam[Naamgrootte];
        std::cout << "Geef een bestandsnaam in" << std::endl;
        std::cin >> Naam;
        std::cout << std::endl;
        std::ofstream outFile(Naam);
        if (!outFile)
        {
            std::cerr << "Kan bestand niet openen" << std::endl;
            exit (1);
        }
        for (int i=0; i<100; i++)
        {
            outFile << d[i] << std::endl;
        }
        outFile.close();    
}

你的问题在这里:

for( double i = 0; i < nl; i++ )
{   
    double j=0; 
    double y = 0.25*(1-tanh(double(j-75)/5));
    j+=Golf_dl;
    pb(T_1)+y; 
}

考虑这样一个事实,即循环变量i没有在循环内的任何地方使用。此外,jy在循环之间不保留它们的值(它们不是static)。