c++ - 插入到 multimap 导致段错误

标签 c++ stl insert segmentation-fault 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;但在下一行出现段错误。

生锈

最佳答案

您实际上从未创建过数据库对象,只是一个指向任何地方的指针(也许您习惯了另一种语言)。

尝试创建一个这样的 database data;

然后将您的 -> 更改为 . 以访问成员。

考虑在 The Definitive C++ Book Guide and List 获取其中一本书

关于c++ - 插入到 multimap 导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5639048/

相关文章:

c++ - 删除 2D vector 中的行 - 段错误

c++ - 在进程之间移动 STL 对象

mysql - Innodb 插入速度非常慢 : 65secs for 1K entries in empty table

c++ - 调试器启动时 VS2012 : Breakpoint in ntdll. dll,没有更多信息

c++ - 在命名空间内的变量之前“使用”

C++ map<K,T> 初始化

php - MySQL 查询错误-没有为准备好的语句中的参数提供数据

java - 从 mysql 插入时出错

c++ - Visual C++ 是否提供与 GCC 中的 `__attribute__((alias))` 具有相同功能的语言结构?

c++ - 在没有 RTTI 的情况下检查 std::any 的类型