Vector in a struct wont let me push_back
Hi i have a vector in a struct as follows for pthreads argument passing:
struct thread_data{
vector< pair < Database, string> > list_databases;
...
...
};
...some more code...
then in a later function when i do the following ( mydata is a thread_data passed into the function ) ( entry being a pair< Database, string > )
mydata->list_databases.push_back(entry);
whenever I do this it tells me that push_back is of non-class type. I dont understand the error. I also tried using:
vector< pair<Database,string> > * list_databases;
and
mydata->list_databases->push_back(entry);
and a combination of the two. All give me the same error. Can anyone suggest something? I've researched this and have been stuck on it for hours. Thank you
edit:
Here is the rest of the code:
#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(st开发者_如何学Pythonore_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;
}
list
is a local variable in the main
function, so it is destroyed when main
returns (on the return 0;
line in main
). You pass the address of this local variable to load_store
, which you start on another thread. If load_store
tries to access list
after list
has been destroyed, bad things happen.
You need to synchronize access to list
, probably by having main
join with thread1
before exiting.
mydata->list_databases.push_back(entry);
, as you've shown in your question, will fail because thread_data::list_databases
is a vector<...>*
rather than a vector<...>
. I.e., it's a pointer-type rather than a class-type, just as the compiler error you're seeing indicates.
mydata->list_databases->push_back(new_store);
, as you've shown in your code sample, should work, except that you need to #include <utility>
in order to use std::pair
.
精彩评论