#include <fstream>
#include <string_view>
#include <unordered_map>
#include "nlohmann/json.hpp"
using json = nlohmann::json;
class Strategy {
private:
int mActionNum;
double mNormSum;
double* mRegretSum;
double* mStrategy;
double* mStrategySum;
double* mAverageStrategy;
public:
Strategy (const int actionNum): mActionNum {actionNum} {
mRegretSum = new double[actionNum];
mStrategy = new double[actionNum];
mStrategySum = new double[actionNum];
mAverageStrategy = new double[actionNum];
for (int a = 0; a < actionNum; ++a) {
mRegretSum[a] = 0.0;
mStrategy[a] = 1.0 / (double) actionNum;
mStrategySum[a] = 0.0;
mAverageStrategy[a] = 0.0;
}
}
~Strategy() {
delete[] mRegretSum;
delete[] mStrategy;
delete[] mStrategySum;
delete[] mAverageStrategy;
}
const double* get(const double weight) {
mNormSum = 0.0;
for (int a = 0; a < mActionNum; ++a) {
mStrategy[a] = mRegretSum[a] > 0 ? mRegretSum[a] : 0;
mNormSum += mStrategy[a];
}
for (int a = 0; a < mActionNum; ++a) {
if (mNormSum > 0) {
mStrategy[a] /= mNormSum;
} else {
mStrategy[a] = 1 / mNormSum;
}
mStrategySum[a] += weight * mStrategy[a];
}
return mStrategy;
}
const double* get_avg() {
mNormSum = 0.0;
for (int a = 0; a < mActionNum; ++a) {
mNormSum += mStrategySum[a];
}
for (int a = 0; a < mActionNum; ++a) {
if (mNormSum > 0) {
mAverageStrategy[a] = mStrategySum[a] / mNormSum;
} else {
mAverageStrategy[a] = 1.0 / (double) mActionNum;
}
}
return mAverageStrategy;
}
};
int main () {
std::ifstream f("/home/tomas/Dropbox/strategy.json");
json data = json::parse(f);
std::unordered_map<std::string_view, Strategy> strategies;
std::string info_set {};
for (auto& e : data) {
info_set = e["cluster"].get<std::string>()
+ ',' + e["history"].get<std::string>();
Strategy strat { static_cast<int>(e["regret_sum"].size()) };
strategies.insert({info_set, strat});
}
return 0;
}
I suppose that the problem is because the instance of the class is destroyed each every cycle, am I correct?
So I tried also something like this:
Strategy createOutOfScope(int size) {
Strategy strat { size };
return strat;
}
int main () {
std::ifstream f("/home/tomas/Dropbox/strategy.json");
json data = json::parse(f);
std::unordered_map<std::string_view, Strategy> strategies;
std::string info_set {};
for (auto& e : data) {
info_set = e["cluster"].get<std::string>()
+ ',' + e["history"].get<std::string>();
strategies.insert({info_set, createOutOfScope(static_cast<int>(e["regret_sum"].size()))});
}
return 0;
}
But of course, I haven't solved it. Can someone explain me how I can save a object in a unordered_map type, and generally how I can create and save an instance of object created out of scope. Thank you very much.