C ++链表在函数之间丢失数据 [英] c++ Linked List losing data between functions

查看:109
本文介绍了C ++链表在函数之间丢失数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用指针和范围时遇到了问题.我正在尝试维护指向对象的链接列表列表.当我尝试在一个函数中使用push_front()时,它可以工作.但是,如果我尝试遍历程序另一部分中的列表,则该列表不再包含任何数据,并且我的指针不正确.

I am having a problem with pointers and scope. I am trying to maintain an array of linked lists of pointers to objects. When I try to push_front() in one function, it works. However, if I try to iterate through the list in another part of my program, the list no longer contains any data, and my pointers are bad.

这是我parseCommands函数的一部分.问题是何时调用printList:

This is part of my parseCommands function. the problem is when printList is called:

                    Administrator *adminPtr = new Administrator(); // create new Administrator pointer

                    //local variables...
                    string adminName;   //administrator's name
                    int adminMNum;  //administrator's M Number
                    string adminEmail;  //administrator's email address
                    string adminTitle;  // administrator's title

                    // read in & store data for new administrator
                    inData >> adminName; //read in data
                    adminPtr->setName(adminName); //set admin name

                    inData >> adminMNum;
                    adminPtr->setMNum(adminMNum);   // set admin M Number

                    inData >> adminEmail;
                    adminPtr->setEmail(adminEmail); // set admin email address

                    inData >> adminTitle;
                    adminPtr->setTitle(adminTitle); //set admin title
                    // finished storing new administrator info

                    // add Administrator to list
                    cout << "Adding Administrator: " << endl;
                    cout << "in records office adminPtr/newPerson: " << adminPtr << endl;
                    universityList.addPerson(adminPtr);  // call addPerson--hashTable
                    //universityList.printPerson(adminPtr);     // print admin info using polymorphic method
                    //cout << "The load factor (alpha) is: " << universityList.getLength()/universityList.getMaxTableSize() << endl;    // print alpha
                    universityList.printList(adminPtr->getMNum());  // print all items at table[loc]--breaks here
                    cout << endl;               

printList可以正常工作的addPerson函数:

The addPerson function where printList works fine:

template <typename T>
void HashTable<T>::addPerson(T newPerson) { //newPerson is a pointer to a person object
  int loc;  // array location provided by hashFunction
  cout << "in hashtable newPerson: " << newPerson << endl;
  loc = hashFunction(newPerson->getMNum());  // get loc
  table[loc].push_front(&newPerson);  // add to list at table[loc] passing address of pointer to person
  printList(newPerson->getMNum());  // print all items at table[loc]--works here
  size++;   // increment size
  } //end function

在addPerson中调用但不在parseCommands中调用时起作用的printList函数:

The printList function that works when called in addPerson, but not in parseCommands:

template <typename T>
void HashTable<T>::printList(searchKeyType key) {   //print list of items held in array location
    int loc = hashFunction(key);    // get array location
    if (table[loc].empty()) {   // if list is empty
        cout << "Can not print person M" << key << " NOT found" << endl << endl; 
    }   //end if empty
  else{
    list<T*>::iterator iter;    // stl iterator
    iter = table[loc].begin();
    cout << "in printList table[loc]begin " << *iter << endl;   //print address of table[loc]begin.()--where iter points
    cout << "in printList item in table[loc]begin " << **iter << endl;  // print address of the pointer that iter points to
    while(iter != table[loc].end()) { // for each item in the list

        (**iter)->print();  // print person info using polymorphic method
        ++iter;
    }   //end for
  } // end else
}   // end printList

打印功能:

void Administrator::print()const {  
// print Administrator info
cout << "   " << "Full Name:    " << getName() << endl;
cout << "   " << "M Number :    "<< getMNum() << endl;
cout << "   " << "Email Addr:   " << getEmail() << endl;
cout << "   " << "Title:        "   << getTitle() << endl;
}; // end print function

hashTable类:

The hashTable class:

template<typename T>
class HashTable{
public:
    HashTable(); // constructor
    bool isEmpty()const; //determines if the hash table is empty
    int getLength() const;  // returns (size) number of Persons in table (accessor)
    int getMaxTableSize() const;    // returns tableSize (size of array)
    void addPerson(T person);   // adds new Person 
    void removePerson(searchKeyType key);   // deletes Person from the HashTable
    void printPerson(T person); // prints Person info
    T getNodeItem(int mNumber); //returns person object (accessor)
    void printList(searchKeyType key);  //print list of items held in array location

private:
    int size;   // number of Persons in table
    static const int tableSize = 1; // number of buckets/array size -- planning on using 70001--assuming 35,000 entries at once; largest prime > 2*35000
    list <T*> table[tableSize]; // array of STL lists for chains
    int hashFunction(searchKeyType searchKey);  // hash function to return location (array index) of item
}; //end HashTable class

我将adminPtr传递给addPerson,并且似乎将其添加到列表中.返回parseCommands函数时为什么会丢失数据?这是堆栈还是堆的问题?我在某个地方需要新"吗?我在那里打印了一些指针的地址,试图弄清楚发生了什么.

I pass adminPtr to addPerson, and it seems to add it to the list. Why am I losing the data when I return to the parseCommands function? Is it a stack vs. heap issue? Do I need "new" somewhere? There are a few extra lines in there where I was printing out the address of the pointers trying to figure out what's going on.

这是我无法解决的类的编程问题.我们必须使用STL链接列表数组模拟哈希表.我们不允许使用向量,地图等.该程序涉及具有派生类(管理员等)的抽象基类(人)和模板化哈希表类.还有一个类(RecordsOffice)保存哈希表.

This was a programming problem for a class that I was unable to resolve. We had to simulate a hash table using an array of STL linked lists. We were not allowed to use vectors, maps, etc. The program involves an abstract base class (Person) with derived classes (Administrator, etc.) and a templated hash table class. There is one more class (RecordsOffice) that holds the hash table.

class RecordsOffice {
public:
    RecordsOffice();    // default constructor
    void parseCommands(string fileName);    // function to parse commands from a file to maintain the StudentList

private:
    HashTable <Person*> universityList; // creates empty hashtable
};

推荐答案

问题出在这两个地方.

The problem is in these two places.

universityList.addPerson(adminPtr); 

//...

您正在传递adminPtr的副本.

You are passing a copy of adminPtr.

template <typename T>
void HashTable<T>::addPerson(T newPerson) { //newPerson is a pointer to a person object
// ...
  table[loc].push_front(&newPerson);  // add to list at table[loc] passing address of pointer to person
// ....
  } 

newPersonaddPerson的局部变量.返回时不再有效.但是您要将它的地址添加到表中.

newPerson is a local variable to addPerson. When it returns it is no more valid. But you are adding it´s address in to the table.

问题在于

list <T*> table[tableSize];

正在存储指向Person指针的指针.

is storing pointers to pointers of Person.

我认为通过引用传递也不能解决问题.因为那样,您将依赖于此处自动创建的指针.

I don't think passing by reference would solve the problem too. Because then you will be dependent on the automatically created pointer here.

Administrator *adminPtr = new Administrator();

adminPtr指针所指向的内容将保留,而adminPtr本身将不保留.因此,您不能依赖于它的地址(除非您仍然沉迷于创建它的同一函数中).解决该问题的一种可能方法是动态分配adminPtr本身.

What adminPtr pointer points to will stay but not adminPtr itself. So you can not depend on its address (unless you are sstill in the same function that created it). One possible way to solve it would be to allocate adminPtr itself dynamically.

Administrator **adminPtr = new Administrator*;
adminPtr = new Administrator();

但是也许您应该修改要求.

But maybe you should revise the requirements.

这篇关于C ++链表在函数之间丢失数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆