如何将结构指针插入stl向量中并显示内容



我在循环中调用一个函数,该函数将参数作为结构指针(st*ptr),我需要将此数据推送回STL向量并在循环中显示内容。我该怎么做?请帮忙。

struct st
{
int a;
char c;
};
typedef struct st st;

function(st *ptr)
{
vector<st*>myvector;
vector<st*>:: iterator it;
myvector.push_back(ptr);
it=myvector.begin();
cout<<(*it)->a<<(*it)->c<<endl;
}

这是正确的吗?我没有得到实际的输出。

代码片段----

void Temperature_sensor::temp_notification()//calling  thread in a class------
{
cout<<"Creating thread to read the temperature"<<endl;
pthread_create(&p1,NULL,notifyObserver_1,(void*)(this));
pthread_create(&p2,NULL,notifyObserver_2,(void*)(this));
pthread_join(p1,NULL);
pthread_join(p2,NULL);
}

void* Temperature_sensor::notifyObserver_1(void *data)
{
Temperature_sensor *temp_obj=static_cast<Temperature_sensor *>(data);   
(temp_obj)->it=(temp_obj)->observers.begin();
ifstream inputfile("temp.txt");//Reading a text file 
while(getline(inputfile,(temp_obj)->line))
{
stringstream linestream((temp_obj)->line);
getline(linestream,(temp_obj)->temperature,':');
getline(linestream,(temp_obj)->temp_type,':');
cout<<(temp_obj)->temperature<<"---"<<(temp_obj)->temp_type<<endl;
stringstream ss((temp_obj)->temperature);
stringstream sb((temp_obj)->temp_type);
sb>>(temp_obj)->c_type;
ss>>(temp_obj)->f_temp;
cout<<"____"<<(temp_obj)->f_temp<<endl;
(temp_obj)->a.temp=(temp_obj)->f_temp;
(temp_obj)->a.type=(temp_obj)->c_type;
cout<<"------------------q"<<(temp_obj)->a.type<<endl;
(*(temp_obj)->it)->update(&(temp_obj)->a);//Calling the function -------
}
输入文件temp.txt20:F30:C40:cetc
void Temperature_monitor::update(st *p) {}//need to store in a vector------

如果使用std::向量,则应该执行以下操作:

std::vector<st> v; //use st as type of v
//read
for(auto const& i : v) {
std::cout << i.param1 << ' ' << i.param2;
}
//push_back
v.push_back({param1, param2});

当然,你可以有两个以上的参数。

您能分享样本输入数据和预期输出吗?使用您的代码,它总是会创建一个新的向量,并在那里放置1个结构对象。如果你想让单个向量存储所有的结构对象,那么在的调用函数中声明向量

看起来您正在用malloc()或类似函数分配void*类型的缓冲区data,然后将data强制转换为Temperature_sensor*。还显示Temperature_sensor是一个具有std::string成员的类,您正试图将其分配并打印。

这将不起作用,因为std::string不是POD类型,因此std::string构造函数从未被实际调用(同样,Temperature_sensor不是POD类型是因为它有非POD成员,因此其构造函数从未被调用)。

要正确构造对象,您需要使用operator new()来代替malloc(),就像一样

Temperature_sensor *tsensor = new Temperature_sensor;
Temperature_sensor *five_tsensors = new Temperature_sensor[5];

使用像std::unique_ptrstd::shared_ptr这样的智能指针而不是直接使用operator new()(和operator delete())会更习惯,使用std::vector是最好/最习惯的。这些方法中的任何一个都将正确地构造所分配的对象。

您还应该强烈考虑大幅简化Temperature_sensor类。它似乎有许多实例变量,它们以不同的格式冗余地存储相同的信息,并且作为函数中的局部变量更有意义。

您也不需要创建所有的std::stringstream;考虑使用std::stod()std::stoi()将字符串转换为浮点或整数,使用std::to_string()将数字转换为字符串。

最新更新