插入地图矢量

Inserting into a vector of maps

我有一个地图向量需要插入其中。这是我的代码中给我错误的部分。请注意,RGB 是一个包含 3 个无符号字符的结构,即红色、绿色和蓝色。当我尝试插入以下代码时,出现以下错误:

support.cpp:231:38:错误:'i' 不能出现在常量表达式中 support.cpp:231:39: 错误:数组引用不能出现在常量表达式中 support.cpp:231:42: 错误:'PPM::img' 不能出现在常量表达式中 support.cpp:231:46: 错误:'i' 不能出现在常量表达式中 support.cpp:231:47: 错误:数组引用不能出现在常量表达式中 support.cpp:231:48: 错误:模板参数 1 无效 support.cpp:231:48: 错误:模板参数 2 无效

我已经尝试在整个 Internet 上搜索解决方案,但我只能通过 switch 语句找到此错误的实例。任何帮助将不胜感激

 vector<map<int, RGB> > timesClosest;
 timesClosest.resize(qcolors.size());

int counts[img.size()];


for (int j = 0; j < qcolors.size(); j++)
{
    int counts[img.size()];
    for (int i = 0; i < img.size(); i++)
    {
        counts[i] = 0;
        if (indexQC[i] == j)
        {
            counts[i]++;
        }
    }
    //now add this to the map
    for (int i = 0; i < img.size(); i++)
    {
        int c = counts[i];
        timesClosest[i].insert(pair<counts[i], img[i]>);


    }

}

您正在插入 timesClosest 的模板参数。插入应该是

timesClosest[i].insert(std::make_pair(counts[i], img[i]));

一个问题是您不能使用表示元素数量的运行时表达式来声明数组。

改为使用 std::vector。无论如何你都在使用它,但出于某种原因,你没有在真正需要使用它的地方使用它:

而不是:

int counts[img.size()];

这样做:

std::vector<int> counts(img.size());