samedi 23 décembre 2017

How to use a pointer to a std::map if the size is unknown?

I'm new to c++ and dynamic memory allocation and doing a small project to learn. I wrote a small class to calculate similarity based on Euclidean distance as below which is working:

Declaration:

class Similarity
{
    std::map<std::string, std::map<std::string, float>> data_;

public:
    Similarity(std::map<std::string, std::map<std::string, float>> data);
    float similarity_euclidean(std::string a, std::string b);
};

Definition:

Similarity::Similarity(std::map<std::string, std::map<std::string, float>> data)
{
    this->data = data;
}

float Similarity::similarity_euclidean(std::string a, std::string b)
{
    float distance_squared = 0;

    std::map<std::string, float> data_a = this->data[a];
    std::map<std::string, float> data_b = this->data[b];

    for (auto const &entry : data_a)
    {
        if (data_b.count(entry.first) > 0)
        {
            distance_squared += (entry.second - data_b[entry.first]) * (entry.second - data_b[entry.first]);
        }
    }
    return (1 / (1 + distance_squared));
}

I heard that if the size required for the variable is unknown beforehand, it's better to use a pointer. So, I'm trying to use a pointer variable in the class like below:

std::map<std::string, std::map<std::string, float>> *data;

And then in the constructor, I'm trying to do something like

this->data = new std::map<std::string, std::map<std::string, float>>[data]

The above is not working, I don't think I'm doing it right the way. My questions are

  1. Is it sensible to use *date in the class instead of data?
  2. How do I do the initialization of *data in the constructor?

I'm doing this project in Visual Studio 2017 as a DLL project. Thanks very much.

Aucun commentaire:

Enregistrer un commentaire