I am working on my version of a genetic algorithm to solve the knapsack problem in C++. I have a map of string to vector like
map<string, vector<int>> objects
{
{"Object 1", {7, 20, 15}},
{"Object 2", {3, 50, 10}},
{"Object 3", {5, 80, 12}},
{"Object 4", {4, 80, 8}},
{"Object 5", {2, 40, 11}}
};
and a vector of vectors
vector<vector<int>> population;
where I will store information such as
population[0] = {0, 0, 1, 1, 0};
population[1] = {1, 0, 0, 0, 1};
population[2] = {1, 0, 1, 0, 1};
...
Each vector is called an individual, and each element of a given individual indicates the presence (1) or the absence (0) of the corresponding object. So, for example, the third individual (population[2]) has Object 1, Object 3 and Object 5.
What I want to do is write a function which will receive an index from population and return the sum of the corresponding values from objects. In the case of population[2] I'd like to have another vector containing {14, 140, 38} (7+5+2, 20+80+40, 15+12+11).
But I'm struggling to access the values of the objects map.
map<string, vector<int>> objects {/*...*/}
vector<vector<int>> population;
void initializePopulation() {/*...*/}
void getScore(vector<int> individual, vector<int>& sum)
{
for(int i = 0; i < 3; i++)
{
sum.push_back(0);
for(int j = 0; j < 5; j++)
{
if(individual[j] == 1)
{
sum[i] += ???;
}
}
}
int main()
{
/*...*/
initializePopulation();
vector<int> sum;
getScore(population[2], sum);
}
So, as you can see, I'm not sure how to proceed with sum[i]. Any suggestions? I'm not very fluent in C++, so a more detailed answer would be appreciated!