c++ - 结构中的 vector 不会让我 push_back

标签 c++ vector struct pthreads

您好,我在结构中有一个 vector ,如下所示用于 pthreads 参数传递:

struct thread_data{
   vector< pair < Database, string> > list_databases;
   ...
   ...
};

...some more code...

然后在稍后的函数中,当我执行以下操作时 (mydata 是传递给函数的 thread_data ) (条目是一对<数据库,字符串>)

mydata->list_databases.push_back(entry);

每当我这样做时,它都会告诉我 push_back 是非类类型。我不明白这个错误。我也尝试使用:

vector< pair<Database,string> > * list_databases;

mydata->list_databases->push_back(entry);

以及两者的结合。都给我同样的错误。任何人都可以提出建议吗?我已经研究过这个并且已经坚持了几个小时。谢谢

编辑:

下面是剩余的代码:

#include<iostream>
#include<pthread.h>
#include<vector>
#include<string>
#include<fstream>

using namespace std;

struct thread_data{
   vector< pair<Database, string> >* list_databases;
   const char* store;
}

void* load_store( void* threadarg );

int main (){
  vector< pair <Database, string> > list;
  pthread_t thread1;
  string test;
  cout <<"$ ";
  cin >> test;

  const char* store_name = test.c_str();

  struct thread_data tester;
  tester.store = store_name;
  tester.list_databases = &list;

  pthread_create(&thread1,NULL,load_store, (void*) &tester);
  return 0;
}

void * load_store( void* threadarg ){
  struct thread_data *mydata;
  mydata = (struct thread_data*) threadarg;
  string store_used = mydata->store;

  ifstream load;
  string conversion;
  Database Loader;
  load.open(store_used.c_str());

  if(!load){ cerr << "Does not exist" << endl;
    exit(1);
  }

  while(!load.eof()){
    //...pushes file contents into database Loader...
  }
  load.close();
  pair < Database, string > new_store(Loader, store);
  mydata->list_databases->push_back(new_store);     // this is where the error occurs
 return 0;
}

最佳答案

listmain 函数中的一个局部变量,所以它在 main 返回时被销毁(在 return 0; main 中的 行)。您将此局部变量的地址传递给在另一个线程上启动的 load_store。如果 load_store 试图在 list 被销毁后访问 list,就会发生不好的事情。

您需要同步对 list 的访问,可能是在退出之前让 main 加入 thread1

关于c++ - 结构中的 vector 不会让我 push_back,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5149880/

相关文章:

c++ - 需要指导 : Vectors of unique_ptr to dervied classes from an abstract base class

c++ - 为什么不通过将指针移动到 vector[0] 来实现 c++ std::vector::pop_front()?

c++ - STXXL多维 vector 使程序卡住

c - 如何使结构成员私有(private)?

c++ - 为什么 C++ 中的字符串通常以 '\0' 结尾?

c++ - 是否为每个不同大小的 std::array 编译了一个全新的类?

C++通过函数指针错误调用成员函数

c++ - 执行时间差异,有吗?

c# - 结构上的扩展方法

json - 如何通过属性将 JSON 对象数组整理成包含每个对象属性向量的结构?