Implementing K-means in C++

0

I would be appreciate if someone could help me! I implement kmeans algorithm in c++.

-The points that I have to split in groups are known.
-I want to make 3 clusters of them.
-But the clusters have to be instantiated randomly in the first time.

When I try it, the following message appears and I can not solve it.

Unhandled exception at 0x00007FF92B484E20 (MengeCore.dll) in menge.exe: 0xC0000005: Access violation writing location 0x0000000000000000.

The problem is in lines when I try to instantiate clusters.

Thank you in advance!!!

#include <cassert>
#include <limits>
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <list>
#include <ostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <stdio.h>

using namespace std;


class Point{

private:
    double x;
    double y;

public:

    Point::Point(double x, double y) : x(x), y(y) {}



    double Point::getX() const {
        return x;
    }

    double Point::getY() const {
        return y;
    }

    Point::Point() {}

    bool Point::operator==(const Point &rhs) const {
        return x == rhs.x &&
            y == rhs.y;
    }

    bool Point::operator!=(const Point &rhs) const {
        return !(rhs == *this);
    }

    friend std::ostream &operator<<(std::ostream &os, const Point &point) {
        os << "(" << point.x << "," << point.y << ")";
        return os;
    }

    double getDistance(Point &p) {
        return sqrt(pow(p.x - this->x, 2) + pow(p.y - this->y, 2));
    }


};

class Cluster {
public:
    Point centroid;
    vector<int> points;

    Cluster::Cluster(const Point &centroid, const vector<int> &points) : centroid(centroid), points(points) {}

    Cluster::Cluster() {
    }

    string getPoints() {
        string s = "";
        for (int p : points) {
            s += to_string(p + 1) + " ";
        }
        return s;
    }


    Cluster::Cluster(const Point &centroid) : centroid(centroid) {}

};  

vector<Point> points{ { 9, 9 },
{ 1, 1 },
{ -1, -1 },
{ 3, 3 },
{ 10, 10 },
{ -2, -2 },
{ 7, 8 },
{ 0.2, 0 },
{-1, 0},
{ 6, 10 } };


vector<Cluster> clusters{};

int main() {


    int K=2;

    for (int i = 0; i < K; i++)
    {
        srand(time(NULL));
        int RandIndex = rand() % 10; //generates a random number between 0 and 9
        //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        //HERE IS THE PROBLEM
        //!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        clusters[i].centroid = points[RandIndex];
    }

return 0;

} 

}  

c++
cluster-analysis
k-means
asked on Stack Overflow Mar 9, 2020 by dani

1 Answer

1

you should did not initialize the size for the cluster vector.

int main() 
{
...
    int K=2;
    clusters.resize(K);
    for (int i = 0; i < K; i++)

...
}
answered on Stack Overflow Mar 9, 2020 by Max

User contributions licensed under CC BY-SA 3.0