增加贴图的值

Increment the value of a map

本文关键字:增加      更新时间:2023-10-16

需要你的帮助,如果你能快速帮助我,那就更好了。这是一个非常琐碎的问题,但仍然无法理解我到底需要在一行中放什么。

下面的代码我有

for (busRequest = apointCollection.begin(); busRequest != apointCollection.end(); busRequest++)
{
    double Min = DBL_MAX;
    int station = 0;
    for (int i = 0; i < newStations; i++)
    {
        distance = sqrt(pow((apointCollection2[i].x - busRequest->x1), 2) + pow((apointCollection2[i].y - busRequest->y1), 2));
        if (distance < Min)
        {
            Min = distance;
            station = i;
        }
    }
    if (people.find(station) == people.end())
    {
        people.insert(pair<int, int>(station, i));
    }
    else
    {
        how can i increment "i" if the key of my statation is already in the map.
    }
}

简单地说,我坐第一辆公共汽车去第二个环路,坐第一个车站,找到最小距离。在我完成第二个循环后,我将距离最小的车站添加到我的地图中。在我进行所有循环之后,如果有同一个站,我需要增加它,所以这意味着该站正在使用两次等等。

我需要帮助,只要给我提示或提供我需要添加的行。

我提前感谢你,等待你的帮助。

我想你指的是Min Distance而不是i?请检查并告诉我。

for (busRequest = apointCollection.begin(); busRequest != apointCollection.end(); busRequest++)
{
    double Min = DBL_MAX;
    int station = 0;
    for (int i = 0; i < newStations; i++)
    {
        distance = sqrt(pow((apointCollection2[i].x - busRequest->x1), 2) + pow((apointCollection2[i].y - busRequest->y1), 2));
        if (distance < Min)
        {
            Min = distance;
            station = i;
        }
    }
    if (people.find(station) == people.end())
    {
        people.insert(pair<int, int>(station, i)); // here???
    }
    else
    {
        // This routine will increment the value if the key already exists. If it doesn't exist it will create it for you
        YourMap[YourKey]++;
    }
}

在C++中,您可以直接访问映射键,而无需插入它。C++将自动使用默认值创建它。在您的情况下,如果people映射中不存在station,并且您将访问people[station],则people[station]将自动设置为0int的默认值为0)

所以你可以这样做:

if (people[station] == 0)
{
    // Do something
    people[station] = station; // NOTE: i is not accessible here! check ur logic
}
else
{
    people[station]++;
}


此外:在您的代码中,不能在IF条件内访问i以插入人员映射。