0

我面临向量下标超出范围错误。我已经设法找到导致问题的代码,但我不知道如何解决它。

定义的变量类型是,

typedef vector <string> v1; //vector string

typedef vector <v1> v2; // vector (v1) to create a double vector

typedef map<string, int> mapstint; //vector (string, int)

typedef vector<int> vint; // vector (int)

typedef vector<double> vd;

代码如下,

string splitgain(v2 &table)
{
    int col, i;

    string coln;
    mapstint map;
    double min = DBL_MAX;
    int splitcol = 0;
    vint eval,nos;

    for (col = 0; col < table[0].size() - 1; col++)
    {
        coln = table[0][col];
        vint counts = countno(table, col);
        vd atteval;
        double colval = 0.0;
        for (i = 1; i < table.size() - 1; i++)
        {
            double val = 0.0;
            if (map.find(table[i][col]) != map.end())
            {
                map[table[i][col]]++;
            }
            else
            {   map[table[i][col]] = 1;
                v2 tempt = prune(table, coln, table[i][col]);

                vint ccounts = countno(tempt, tempt[0].size() - 1);
                int j, k;
                for (j = 0; j < ccounts.size(); j++)
                {
                    double temp = (double)ccounts[j];
                    val -= (temp / ccounts[ccounts.size() - 1])*(log(temp / ccounts[ccounts.size() - 1]) / log(2));
                }
                atteval.push_back(val);
                val = 0.0;
            }
        }

        //------THIS IS WHERE THE ERROR IS COMING FROM-------

        for (i = 0; i < counts.size() - 1; i++)
        {
            colval += ((double) counts[i] * (double) atteval[i]);
        }
        //----------------------------------------------------

        colval = colval / ((double)counts[counts.size() - 1]);
        if (colval <= min) 
        {
            min = colval;
            splitcol = col;
        }
    }
    return table[0][splitcol];
}
4

1 回答 1

1

请注意编译器的警告(或提高警告级别)

所有循环

for (col = 0; col < table[0].size() - 1; col++)

对于 (i = 1; i < table.size() - 1; i++)

对于 (i = 0; i < counts.size() - 1; i++)

是麻烦。

注意 std::size_t(0) - 1 == std::numeric_limits::max()

于 2013-11-14T18:52:10.353 回答