加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 从向量返回底层数组

发布时间:2020-12-16 10:44:51 所属栏目:百科 来源:网络整理
导读:阵列是否会被释放,如果是,那么解决方法是什么? double * GetArrayFromVector( std::mapstd::string,double m,char ** names,int count ){ if(!names) return 0; std::vectordouble vec(m.size()); for (int i=0; icount; ++i) { if(!names[i]) return 0; st
阵列是否会被释放,如果是,那么解决方法是什么?

double * GetArrayFromVector( std::map<std::string,double> m,char ** names,int count )
{ 
    if(!names) return 0;

    std::vector<double> vec(m.size());
    for (int i=0; i<count; ++i)
    { 
       if(!names[i]) return 0;
       std::map<std::string,double>::iterator iter=m.find(name[i]);
       if(iter!=m.end())
          vec.push_back(iter->second);
       else
         return 0;   
    }

    return &vec[0]; 
}

非常感谢

解决方法

将你的功能分成两部分.
让您的功能只做一个动作:
1.从地图填充矢量.
2.从vector创建数组.
不要忘记通过const引用传递map.

主要注意事项:GetArrayFromVector的调用者负责内存释放.

void FillVector( const std::map<std::string,double>& m,std::vector< double >& v,int count )
 {
       .......
 }

 double* createArray( const std::vector< double >& v )
 {
     double* result = new double [v.size()];

     memcpy( result,&v.front(),v.size() * sizeof( double ) );

     return result; 
 }  

 // and finally your function

 double* GetArrayFromVector( const std::map<std::string,int count )
 {
      std::vector< double > v;
      FillVector( m,v,names,count );

      return CreateArray( v );
 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读