c++ - vector 迭代器不可取消引用,同时尝试从文件中读取

标签 c++ visual-c++ vector

我正在使用 vector 将数据(结构)写入文件,当我尝试使用 vector 迭代器检索数据时,它给出了:“Vector iterator is not dereferenceable.”

这是我的代码:

void CProgram_1_STLDlg::OnBnClickedBtnView()
{
    // TODO: Add your control notification handler code here
    CFile file;
    CFileException e;
    studentVector::iterator sit;
    studentVector::iterator sBegin = sVector.begin();
    studentVector::iterator sEnd = sVector.end();

    CString path = _T("D:\\Student.txt");

    if ( file.Open(path, CFile::modeRead, &e) ) {
        while ( file.Read( (char *)&sVector, sizeof(sVector)) ) {
            AfxMessageBox(_T("File opened in read mode."), MB_ICONINFORMATION);
            AfxMessageBox(_T("ID:\t")+sit->id+L"\nName:\t"
                           +sit->name+L"\nMarks:\t"+sit->marks+L
                          "\nPercentage:\t"+sit->per+L"\nState:\t"+sit->state);
            sit++;
        }
        //file.Read( (char *)&sData, sizeof(sData));

        /*for ( sIterator = sVector.begin(); sIterator != sVector.end(); sIterator++ ) {
                //AfxMessageBox(_T("ID:\t")+sIterator->id+L
                                "\nName:\t"+sIterator->name+L"\nMarks:\t"
                                +sIterator->marks+L"\nPercentage:\t"+sIterator->per+L
                               "\nState:\t"+sIterator->state);
                //AfxMessageBox(_T("Hello..Testing...!"));
        }
*/

    } else {
        AfxMessageBox(_T("Error! Unable to open file."), MB_ICONERROR);
    }
}

现在我不知道如何解决这个错误。

注意:我引用了一些谷歌给我的链接,但我无法解决我的问题。

最佳答案

您不能简单地覆盖 vector 的内存。这几乎肯定会破坏您的流程。

此外,您永远不会将任何东西分配给 sit 并期望它包含一些合理的东西。

您需要解析 Student.txt 中的数据并使用 vector 的成员函数将其填充为合理的数据。作业可能会告诉您文件的外观,以便您可以对其进行解析。

关于c++ - vector 迭代器不可取消引用,同时尝试从文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34850732/

相关文章:

C++ 类不是自身的基础

C++ 通过引用传递对象?

c++ - 为什么只有在虚函数的情况下才需要虚表?

c++ - 为什么必须在运算符重载中提供关键字 const

c++ - 如何从文件读取和写入 AES key ?

java - 使用 cygwin 为 JNI (Android NDK) 编译 C++ 代码

c# - 实时通讯

c++ - 节流 C++ 线程

c++ - string[] 还是 vector<string>?

r - 我可以使用正则表达式创建向量吗?