处理课程数

Handling arrays of classes

本文关键字:程数 处理      更新时间:2023-10-16

我遇到了这个问题,您将不得不创建一个数据库类型的程序,该程序根据他们的胜利和损失点在团队名称为字符串的情况下存储各个团队的分数。但是,拥有一系列课程并搜索整个集合以找到确切的团队名称并修改分数非常慢且耗时。有更好,有效的方法吗?

std::map对此有效。这样的东西。

#include <iostream>
#include <map>
#include <string>
int main()
{
    // team name and scores
    // std::map has std::pair as its elements
    std::map<std::string, int> teams{ {"team1", 300}, {"team2", 500}, {"team3", 100} };
    teams["team2"] = 0; // set team2's score to 0
    teams["team4"] = 1000; // new team with score of 1000
    for (const std::pair<std::string, int>& pair : teams) // auto will work
        std::cout << pair.first << ": " << pair.second << 'n';
}

输出:

team1: 300
team2: 0
team3: 100
team4: 1000

我的c 不是最新的,为什么不创建一个提供存储对象类集合/数组的功能的第二类,并提供了从集合中找到对象的清洁功能,将其作为返回参数传递给?

class teams {
    int x;
public:
    team getTeamByName(char teamName[20]);
    // Add other methods to add or remove teams...
private:
    team gTeams[10];
};
team getTeamByName(char pTeamName[20]) {
    for(int i = 0; i < gTeams.length; i++) {
        if gTeams[i].teamName = pTeamName
            return gTeams[i];
    }
    return null;
};

我说我的c 有点生锈,因为一段时间没有触摸它,但是创建包装程序类以包含搜索功能使代码清洁并减少重复代码。

上面的课程也将使自己也管理团队列表,以添加代码以在数组中添加团队并删除它们也将有助于创建干净易于阅读的代码。

如果存在句法错误,请原谅上述代码

p