P
Philip Ogunbona
This code is an implementation of class member function. The whole code
where the class and the member function is being used compiles and works
as expected. The problem is that I am returning a pointer to a container
I created in this member function and I have not DELETED it. Does
this not constitute a memory leak? How do I get around it without
changing the signature of the member function?
Regards,
Philip O.
Code implementation of member function.
=======================================
vector<int> * kNN::classify(vector<vector<double> > &testvector)
{
vector<int> *classVector = new vector<int>(testvector.size());
vector<pair<int,double> > distance(numFeatures); // numFeatures is a
data member of class kNN
for (int i =0; i < testvector.size(); i++)
{
for (int j = 0; j < numFeatures; j++)
{
// pick up the class of the feature; it is the last element of the vector
distance[j].first = int(trainData[j][vecLen-1]);
//compute L2 distance between probe/testvector and each of the
training vector
distance[j].second = euclidean(testvector, trainData[j]);
}
//sort the distance vector in ascending order of magnitude
stable_sort(distance.begin(), distance.end(), lessDistance());
//pick the class with the most appearance in the top k entries
(*classVector)=k_vote(distance);
}
#ifdef DEBUG
copy((*classVector).begin(), (*classVector).end(),
std:
stream_iterator<int>(cout, " "));
cout << endl;
#endif
return classVector;
}
where the class and the member function is being used compiles and works
as expected. The problem is that I am returning a pointer to a container
I created in this member function and I have not DELETED it. Does
this not constitute a memory leak? How do I get around it without
changing the signature of the member function?
Regards,
Philip O.
Code implementation of member function.
=======================================
vector<int> * kNN::classify(vector<vector<double> > &testvector)
{
vector<int> *classVector = new vector<int>(testvector.size());
vector<pair<int,double> > distance(numFeatures); // numFeatures is a
data member of class kNN
for (int i =0; i < testvector.size(); i++)
{
for (int j = 0; j < numFeatures; j++)
{
// pick up the class of the feature; it is the last element of the vector
distance[j].first = int(trainData[j][vecLen-1]);
//compute L2 distance between probe/testvector and each of the
training vector
distance[j].second = euclidean(testvector, trainData[j]);
}
//sort the distance vector in ascending order of magnitude
stable_sort(distance.begin(), distance.end(), lessDistance());
//pick the class with the most appearance in the top k entries
(*classVector)=k_vote(distance);
}
#ifdef DEBUG
copy((*classVector).begin(), (*classVector).end(),
std:
cout << endl;
#endif
return classVector;
}