Multidimensional vector subscript out of range

144 views Asked by At

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.

1

There are 1 answers

1
Jarod42 On

You have to check size before accessing element, so it seems you invert your loop.
The following may help:

std::vector<double> Cluster::getCentroid()
{
    std::vector<double> centroid;
    for (int i = 0; i != cluster.size(); i++)
    {
        double temp = 0;

        for (int j=0; j != cluster[i].size(); j++)
        {
            temp+=cluster[i][j];
        }
        centroid.push_back(temp / cluster.size());
    }
    return centroid;
}

And you can simplify it by using STL:

std::vector<double> Cluster::getCentroid()
{
    std::vector<double> centroid;
    for (const auto& c : cluster) {
        centroid.push_back(std::accumulate(c.begin(), c.end(), 0.0) / cluster.size());
    }
    return centroid;
}