2011-04-12 117 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