C++ 将结构向量传递给参数中带有void*的函数

C++ 将结构向量传递给参数中带有void*的函数,c++,vector,stl,C++,Vector,Stl,继续我的最后一个问题,关于将结构向量传递给参数中带有void*的函数,我还面临另一个问题 #include <iostream> #include <vector> struct MMT { int a; char b; int * data; } int func(void *structPtr){ //use the structure member } int main () {

继续我的最后一个问题,关于将结构向量传递给参数中带有void*的函数,我还面临另一个问题

  #include <iostream>
  #include <vector>
  struct MMT
  {
     int a;
     char b;
     int * data;
  }
  int func(void *structPtr){
     //use the structure member
  }
  int main ()
  {
      std::vector<MMT*> myvector;


      for (int i=1; i<=5; i++){
           MMT *mmt;
           mmt->a = i;
           mmt->b = 'a';
           myvector.push_back(MMT);
      }
      std::cout << "myvector contains:";
      for (std::vector<int*>::iterator it = myvector.begin() ; it !=myvector.end(); ++it)
      {
        func((void*)it);//?????????//how to pass structure
      }
      std::cout << '\n';
      return 0;
  }
#包括
#包括
结构MMT
{
INTA;
字符b;
int*数据;
}
int func(void*structPtr){
//使用结构件
}
int main()
{
std::vector myvector;
对于(int i=1;ia=i;
mmt->b='a';
myvector.push_back(MMT);
}

std::cout您的代码存在多个问题,例如您没有分配内存,其次它本身是一个迭代器/指针,因此您需要按如下方式更改代码:

  #include <iostream>
  #include <vector>
  #include <memory>
  struct MMT
  {
     int a;
     char b;
     int * data;
  };
  int func(void *structPtr){
     //use the structure member
  }
  int main ()
  {
      //Better to use smart pointers so no need to manage memory
      std::vector<std::unique_ptr<MMT>> myvector;


      for (int i=1; i<=5; i++){

           myvector.push_back(std::unique_ptr<MMT>(new MMT{i,'a'}));
      }
      std::cout << "myvector contains:";
      for (std::vector<std::unique_ptr<MMT>>::iterator it = myvector.begin() ; it !=myvector.end(); ++it)
      {
        func((void*)(it->get()));
      }
      std::cout << '\n';
      return 0;
  }
#包括
#包括
#包括
结构MMT
{
INTA;
字符b;
int*数据;
};
int func(void*structPtr){
//使用结构件
}
int main()
{
//最好使用智能指针,这样就不需要管理内存
std::vector myvector;

对于(int i=1;我为什么要使用
void*
而不是只传递
const std::vector&
?这里有很多问题-为什么要尝试将
MMT*
s视为
int*
s,然后
void*
s,然后返回到
MMT*
s?!只需坚持对象的实际类型!有多个I请先修复代码中的其他错误。一旦修复了这些错误,问题就在于如何正确应用和取消引用运算符的地址。看起来您正试图通过反复试验来了解指针。请改用。还有,为什么要让函数将
void*
作为参数?您真的应该这样做不要在C++中这样做。如果你想要一个“泛型”可以采用多种不同类型的函数,请使用模板。如果该函数只应采用结构作为参数,请使用适当的结构类型。@Tyker这只是示例代码,我在末尾为OP添加了注释,以便他在实际代码中调用delete,但最好在此处演示智能指针的用法,我将补充理解t在不删除的情况下显示new不利于操作感谢您指出内存泄漏,我知道我刚才提供的代码不是我正在处理的实际代码,是的,我已经处理了MMT*MMT=new MMT();和内存释放的情况