结构中的向量不会让我 push_back [英] Vector in a struct wont let me push_back
问题描述
我在结构中有一个向量,用于 pthreads 参数传递:
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...
然后在稍后的函数中执行以下操作( mydata 是传递给函数的 thread_data )(条目是一对<数据库,字符串>)
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);
每当我这样做时,它都会告诉我 push_back 是非类类型.我不明白这个错误.我也尝试使用:
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;
和
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
其余代码如下:
#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;
}
推荐答案
mydata->list_databases.push_back(entry);
,正如您在问题中所示,将失败,因为 thread_data::list_databases
是一个 vector<...>*
而不是 vector<...>
.即,它是指针类型而不是类类型,正如您看到的编译器错误所指示的那样.
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);
,正如您在代码示例中所示,应该可以工作,只是您需要 #include
以便使用 std::pair
.
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
.
这篇关于结构中的向量不会让我 push_back的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!