2011-04-12 55 views
0

我正在使用我自己的類中使用multimaps的項目,我已經遇到了段錯誤。以下是我的代碼中與該問題有關的部分。我真的很感謝一些幫助。謝謝。插入到multimap導致段錯誤

這裏是database.h

#include <iostream> 
#include <map> 

using namespace std; 

class database{ 
public: 
    database(); // start up the database            
    int update(string,int); // update it            
    bool is_word(string); //advises if the word is a word        
    double prox_mean(string); // finds the average prox         
private: 
    multimap<string,int> *data; // must be pointer          
protected: 

}; 

這裏是database.cpp

#include <iostream> 
#include <string> 
#include <map> 
#include <utility> 

#include "database.h" 

using namespace std; 


// start with the constructor            
database::database() 
{ 
    data = new multimap<string,int>; // allocates new space for the database 
} 

int database::update(string word,int prox) 
{ 
    // add another instance of the word to the database      
    cout << "test1"<<endl; 
    data->insert(pair<string,int>(word,prox)); 
    cout << "test2" <<endl; 
    // need to be able to tell if it is a word         
    bool isWord = database::is_word(word); 
    // find the average proximity            
    double ave = database::prox_mean(word); 

    // tells the gui to updata             
    // gui::update(word,ave,isWord); // not finished yet      

    return 0; 
} 

這裏是TEST.CPP

#include <iostream> 
#include <string> 
#include <map> 

#include "database.h" //this is my file            

using namespace std; 

int main() 
{ 
    // first test the constructor              
    database * data; 

    data->update("trail",3); 
    data->update("mix",2); 
    data->update("nut",7); 
    data->update("and",8); 
    data->update("trail",8); 
    data->update("and",3); 
    data->update("candy",8); 

    // cout<< (int) data->size()<<endl;            

    return 0; 

} 

非常感謝。它編譯並運行到cout << "test1" << endl;,但在下一行中有segfaults。

生鏽

回答

1

您需要在開始在其上插入數據之前分配數據庫。

變化:

database *data;

到:

database *data = new database();

或:

database data;

main()

編輯:如果您使用後者,請在隨後的方法調用中將->更改爲.。否則,在使用它之後,請記住delete您的data對象。

+0

'delete',不是'free()',因爲它被分配了'new'。 – Yexo 2011-04-12 18:25:57

+0

哎呀!謝謝。習慣的力量(使用'malloc')。 – 2011-04-12 18:32:11

+0

它工作。真棒。非常感謝你。 – Rusty 2011-04-13 00:20:07

5

你從來沒有真正創建一個數據庫對象,只是無處(也許你已經習慣了另一種語言)的指針。

嘗試創建一個這樣的database data;

,然後改變你的->.訪問的成員。

請考慮從The Definitive C++ Book Guide and List獲取其中一本書。

+0

感謝您的建議。我現在正在上一堂課,但這位教授真的在吹噓很多東西。我很高興能在夏天坐下來深入瞭解。 – Rusty 2011-04-13 00:21:07