Re: return an undelining array from vector
Yes, it will be deallocated upon returning and if the caller tries to
use that address it will lead to unpredictable results, most likely a crash.
A possible solution is to let the caller build the vector object and
pass it by reference to the function which fills it and then returns.
std::vector<double> vec;
if(GetArrayFromVector(m,names,count,vec)) {
// ...
}
where:
bool GetArrayFromVector( std::map &m, char ** names, int count,
std::vector<double> &vec)
{
if(!names) return 0;
vec.clear();
for (int i=0; i<count; ++i) {
if(!names[i]) return 0;
map<std::string, double>::iterator iter=m.find(name[i]);
if(iter!=m.end())
vec.push_back(iter->second);
else
return 0;
}
return true;
}
another possible solution is to allocate memory for the array and fill
it with the vector content. At that point, the caller is in charge to
deallocate the array.
double * GetArrayFromVector( std::map &m, char ** names, int count )
{
if(!names) return 0;
vector<double> vec;
for (int i=0; i<count; ++i)
{
if(!names[i]) return 0;
map<std::string, double>::iterator iter=m.find(name[i]);
if(iter!=m.end())
vec.push_back(iter->second);
else
return 0;
}
double *tmp = new double[ vec.size() ]
if(tmp) memcpy(tmp,&vec[0],sizeof(double) * vec.size());
return tmp;
}
Also I would suggest you to pass the std::map to the function by
reference and not by value.
Finally, pay attention to the vector constructor because if you call it
with m.size() and then you push_back elements, you end up with a vector
of size m.size() + k, where k is the number of push_backs made and the k
elements are located from m.size() to m.size() + k which is probably not
what you want.
Regards,
Giuliano Bertoletti.
puzzlecracker ha scritto:
Will the array be deallocated and if so, what is a workaround?
double * GetArrayFromVector( std::map m, char ** names, int count )
{ if(!names) return 0;
vector<double> vec(m.size());
for (int i=0; i<count; ++i)
{
if(!names[i]) return 0;
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];
}
Thanks a lot