当前位置: 代码迷 >> VC >> 结构体中的vector<struct> 如何定义,如何使用
  详细解决方案

结构体中的vector<struct> 如何定义,如何使用

热度:6985   发布时间:2013-02-25 00:00:00.0
结构体中的vector<struct>, 怎么定义,怎么使用?
我想实现动态定义数组,所以我用vector
typedef struct{
unsigned short pt[100];
}USHORT1D;
typedef struct{
USHORT1D line[200];
}USHORT2D;
typedef struct{
    vector<PLANE_OF_USHORT> zz;
}INFO;

INFO* inf;

void aaa(void* buffer){

USHORT2D *tmp = (USHORT2D*)malloc(sizeof(USHORT2D));
memcpy( tmp, buffer, sizeof(USHORT2D));
planes__->zz.push_back(*tmp);//为什么每次到这里都有问题,是不是vector用法错误??到底该怎么

}

int main(){

  inf=(INFO*)malloc(sizeof(INFO));
  do{
  ...获得 buffer,方法省略
  aaa(buffer);
  }while(blabla);

  return 0;
}

谢谢大侠帮我看看

------解决方案--------------------------------------------------------
看了你的程序,但是不想改动你的程序。
vector用法如下
typedef struct 
{
int a;
int b;
}AA;

typedef std::vector<AA> AAListType;

int main()
{
AAListType aaArray;
AA aa;
aaArray.push_back(aa);
}

对于你的程序没有必要做malloc,因为你存的是变量的本身,stl会做拷贝的
一般在存储指针的情况下采用malloc/new 
比如

typedef std::vector<AA*> AAListType;

int main()
{
AAListType aaArray;
AA* aa = (AA*)malloc(sizeof(AA)); 
aaArray.push_back(aa);
}

如果把上面的改成下面
int main()
{
AAListType aaArray;
AA aa; // = (AA*)malloc(sizeof(AA)); 
aaArray.push_back(&aa); // 注意如果离开main函数,以后将无法读取这个aa,因为它的生命周期已经结束,内存已经释放,指针将是无效指针。
}


对于你的程序我的提议是 由于结构体比较大,推荐采用存储指针的方式,不需要多2次拷贝,耗资源不说还影响效率。
我觉得我说的已经够详细了

  相关解决方案