I'm trying to write a program with a class Cluster, which has a vector of vector of doubles. When trying to find the Centroid (average point) I'm getting an error.
The idea is to get the value of the first coordinate, then second, third, etc. Of each coordinate in the array, average them, and push them into the centroid object then return it.
The code to find the centroid is below
vector<double> Cluster::getCentroid()
{
double temp;
for(int i=0; i<cluster[i].size();i++)
{
temp=0;
for(int j=0;j<cluster.size();j++)
{
temp+=cluster[j][i];
}
centroid.push_back(temp/cluster.size());
}
return centroid;
}
where centroid is a vector, a private member of the Cluster class.
The error I'm getting is:
"expression: subscript out of range"
I would appreciate any feedback, or any suggestions on what may be causing the problem.
You have to check size before accessing element, so it seems you invert your loop.
The following may help:
And you can simplify it by using STL: