这是我目前正在使用的代码
template <class T>
float Knapsack<T>::knapTable()
{
const int MAXSIZE = 40000;
int temps = nObjects - 1;
float** memoize = new float*[MAXSIZE];
for(int y = 0; y < weight[nObjects]; y++)
memoize[nObjects][y] = 0;
for(int y = weight[nObjects]; y < knapCap; y++)
memoize[nObjects][y] = price[y];
for(int i = temps; i >= 1; i--)
{
for(int y = weight[i]; y < knapCap; y++)
memoize[i][y]= max(memoize[i+1][y], (memoize[i+1][y-weight[i]]+price[i]));
}
return memoize[1][nObjects];
}
出于某种原因,我不断收到错误消息:knapsack.hpp:68:64: error: invalid types 'float*[float]' for array subscript。
就是这一行: float** memoize = new float*[MAXSIZE];
由于某种原因,编译器似乎将 MAXSIZE 识别为浮点数,它是一个 const int。
有没有办法解决这个问题?
编辑了更多代码头文件#ifndef KNAPSACK_H #define KNAPSACK_H
#include <stdexcept>
#include <assert.h>
#include <iostream>
#include <limits.h>
using namespace std;
template <class T>
class Knapsack
{
private:
float knapPrice;
int knapCap, nObjects;
float weight[40000];
float price[40000];
public:
Knapsack(): knapPrice(0), knapCap(0), nObjects(0) {}
~Knapsack() {knapPrice = 0; knapCap = 0;}
float knapFull (int position, int currentCap);
float knapTable ();
float greedyKnap (int currentCap);
float max(float noAdd,float addOb);
void printPrice();
//valueized and valued are modified versions of mergeSort and merge
//designed to sort two arrays by a fraction of the two.
void valueize(int ini, int last);
void valued(int ini, int middle, int last);
void fillWandP();
void setNObjects(int n);
void setKnapCap(int boom);
};
#include "knapsack.hpp"
#endif
主函数 //虽然我不认为这会影响它 #include "sortClass.h" #include "knapsack.h" #include #include #include #include using namespace std;
//mergeSort main;
int main()
{
Knapsack<float> a;
float sacked = 0;
int nO = 18;
int cap = 700;
a.setNObjects(nO);
a.setKnapCap(cap);
a.fillWandP();
for(int b = 0; b <3800000; b++)//for getting good times
sacked = b;
int startAll = clock()*1000000;
sacked = a.knapFull(1, cap);
int knapped = clock()*1000000;
int boom = a.knapTable();
int tabled = clock()*1000000;
a.valueize(1, cap);
int andDone = a.greedyKnap(cap);
int greedified = clock()*1000000;
cout<<startAll<<endl;
greedified = greedified - tabled;
tabled = tabled - knapped;
knapped = knapped - startAll;
cout<<"Recursion profit:"<<sacked<<" Time: "<<knapped<<endl;
cout<<"Memoization profit:"<<boom<<" Time: "<<tabled<<endl;
cout<<"Greedy profit: "<<andDone<<" Time: "<<greedified<<endl;
return 0;
}