这是我目前正在使用的代码

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:错误:数组下标的类型为“float * [float]”无效。

就是这一行:float ** memoize = new float * [MAXSIZE];

由于某种原因,编译器似乎将MAXSIZE识别为浮点数,它是const int。

有办法解决这个问题吗?

编辑更多代码
头文件
#ifndef KNAPSACK_H
#定义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”
#包括
#包括
#包括
#包括
使用命名空间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;
}

最佳答案

weightfloat weight[40000]中声明为class Knapsack

然后,您可以使用weight元素作为memoize函数中knaptable()的索引:

memoize[i][y]= max(memoize[i+1][y], (memoize[i+1][y-weight[i]]+price[i]));
//                                                  ^^^^^^^^^

根据记录,这是g++ 4.6.1产生错误的行;它不指向声明memoize的行。

10-08 18:42