0

尽可能简单地询问任何人都可以解释为什么这个代码:

LinkedListByGrade::LinkedListByGrade(vector<Node> myNodes) {
int lowestGradeFound = myNodes[0].getGrade();
Node *pFristNode = new Node();
cout << "New node created" << endl;
for (size_t i = 0; i <= myNodes.size(); i++) {
    if (myNodes[i].getGrade() < lowestGradeFound) {

        cout << "if triggered" << endl;
        lowestGradeFound = myNodes[i].getGrade();
        pFristNode->reassasignNode(myNodes[i].getFristName(),
                myNodes[i].getLastName(), myNodes[i].getId(),
                myNodes[i].getGrade());
        cout << "int reassassigned" << endl;
    }

给我这个错误:

1 [main] Project 972 exception::handle: Exception: STATUS_ACCESS_VIOLATION 
2130 [main] Project 972 open_stackdumpfile: Dumping stack trace to Project.exe.stackdump

以及如何解决它的想法?

(对不起,我留在了诊断打印语句中。)

这也是影响 myNodes 的唯一代码:

vector<Node> Students;
Node node1("Bobby", "zilch",28,55);
Node node2("Evil", "Dentist",308,55);
Node node3("Raz", "Buton",10,55);
Students.push_back(node1);
Students.push_back(node2);
Students.push_back(node3);

cout<<"stuff"<<endl;
 LinkedListByGrade myList = LinkedListByGrade(Students);
4

1 回答 1

1

我不能肯定地说,但是您正在访问未分配给您的内存,因此很可能您正在运行myNodes. 将能够通过使用调试器来确定这一点。

我可以肯定地说,在您调用的函数的第一行中:

int lowestGradeFound = myNodes[0].getGrade();

如果 中没有项目myNodes,那么这应该会导致访问冲突。

而且您肯定会myNodesfor-loop 的末尾运行,因为您正在访问myNodes[myNodes.size()].

尝试这样的事情:

LinkedListByGrade::LinkedListByGrade(vector<Node> const& myNodes) {
    // Pass by const-reference! ------------------^

    // Set this to something high. Don't access the vector, in case there are no
    // elements therein:
    int lowestGradeFound = std::numeric_limits<int>::max();

    // Where is this deleted?
    Node *pFirstNode = new Node();

    // Use iterators, not indices for looping over a container...
    for (vector<Node>::iterator i = myNodes.begin(), end = myNodes.end(); != end; ++i)
    {
        // Access element by `i->`
        if (i->getGrade() < lowestGradeFound)
        {
            // Now you can assign this safely...
            lowestGradeFound = i->getGrade();
            pFirstNode->reassasignNode(
                i->getFirstName(),
                i->getLastName(),
                i->getId(),
                i->getGrade());
        }
    }

    // [...]
}

但是你真的,真的需要学习使用你的调试器!

于 2013-02-23T03:06:16.130 回答