首页 > 解决方案 > 无法获取位于地图内的当前矢量大小

问题描述

首先,我需要感谢 @jvn91173 对我之前在嵌套循环中访问向量值的另一个问题的帮助。为了避免一些混乱,我将只使用他建议的代码(基于我提供的一些代码,由于我命名一些变量的方式在某些地方不太清楚)以及我现在遇到的问题。

在下面的代码中,我试图根据团队对手的平均功率等级计算调整后的功率等级。我将一个团队的初始实力排名减去其对手的平均实力排名,得出一个调整后的实力排名。Map(string, vector(string)) 命名的对手包含球队名称和其对手的向量列表。我在他/她的建议中添加了一些代码。问题是它会正确计算第一支球队,但其余球队计算不正确。这是由于最内层循环中的变量 summedOpponentPowerRankings 将前一个团队的总额定功率数字添加到当前团队。它也对当前列表大小执行此操作。例如,假设您有 3 支球队,每支球队有 2 个对手,所有 3 支球队的功率等级均为 100.0。

void PowerRankings::calcAllTeamPRWSOS(Teams &t) {

map<string, vector<string>>& opponents = t.getOpponents();
 map<string, float>  oppPowerRankings = calcAllTeamPrePRWSOS(t);// unadjusted power rankings calc here
map<string, float> allTeamPowerRatingWSOS;

string SOSorNot = "WSOS";
ResultsDisplay rd;
PowerRankings pr;
float summedOpponentPowerRankings = 0.0;
int newListSize = 0;
int previousListSize=0;

    for (const auto& opponentsIt : opponents) {

        // You can place an ampersand after the type (creating a reference) to avoid
        // making an unnecessary copy of the variable, increasing performance
        const std::string& teamName = opponentsIt.first;
        const std::vector<std::string>& opponentList = opponentsIt.second;
        float previousSummedOpponentPowerRankings = summedOpponentPowerRankings;
        int currentListSize = opponentList.size() - previousListSize;

        for (const auto& opponent : opponentList) {
            summedOpponentPowerRankings += oppPowerRankings[opponent];
        }
        float selectedTeamSummedOppPowerRankings = summedOpponentPowerRankings - previousSummedOpponentPowerRankings;
        int previousListSize = opponentList.size();
        float avgPowerRanking = selectedTeamSummedOppPowerRankings / currentListSize;

        float selectedTeamPowerRanking = oppPowerRankings[teamName];
        float selectedTeamAdjustedTeamPowerRanking =
            avgPowerRanking - 100 +
            selectedTeamPowerRanking;  



    allTeamPowerRatingWSOS.insert(pair<string, float> (teamName, selectedTeamAdjustedTeamPowerRanking));

}
pr.setAllTeamsPRWSOS(allTeamPowerRatingWSOS);
rd.displayAllTeamPowerRankingResults(SOSorNot, t, pr);

}

标签: c++

解决方案


这肯定是错误的:

for (int i = 0; i <= oppName.size(); i++)

尝试:

for (int i = 0; i < oppName.size(); i++)

如果您允许i到达,您将很难在以后oppName.size()尝试。oppName[i]如果oppName(可能应该是oppNames,因为它似乎是一个包含名称的容器)是一个支持迭代的容器,那么begin/end迭代会更安全:

for(auto it = oppName.begin(); it != oppName.end(); ++it)

oppPowerRanking = oppPowerRankings.find(*it)->second;

如果你喜欢 C++11,你甚至可以:

for(const auto &on : oppName)

oppPowerRanking = oppPowerRankings.find(on)->second;

为了更清晰的意图。

这个:

avgPowerRanking = totalPowerRanking / totalTeams;

是可疑的。totalTeams可能等于零,您将得到除以零错误。所以也许检查一下:

if (totalTeams != 0) { ... }

编辑:感谢@paddy 发现我的错误!


推荐阅读