C++压缩两个for循环提高效率

标签 c++ arrays

我有一个结构数组,我需要从中检索数据。该数组包含姓名和分数。

对于一个函数,我必须输出最高分和关联的名称。如果有多个案例,我必须输出所有名称。

我不能使用 vector 或列表。 (否则我会)我只想在同一步骤中执行这两个操作。

我是这样处理的:

void highScorer (  player array[], int size )
{ // highScorer

    int highScore = 0; //variable to hold the total score

    // first loop determines highest score
    for ( int i = 0; i < size; i++ ) {

        if ( array[i].pointsScored > highScore ) {
            highScore = array[i].pointsScored;            
        }
    }
    cout << "\nThe highest scoring player(s) were:\n";
    // second loop finds players with scores matching highScore and prints their name(s)
    for ( int i = 0; i < size; i++ ) {
        // when a match is found, the players name is printed out
        if ( array[i].pointsScored == highScore ) {
            cout << array[i].playerName;
            cout << ", scored ";
            // conditional will output correct grammar
            if ( array[i].pointsScored > 1 ) {
                cout << array[i].pointsScored << " points!\n";
            }
            else {
                cout << array[i].pointsScored << " point!\n";
            }
        }
    }
    cout << "\n"; // add new line for readability
    return;

} // highScorer

我想将其压缩为一个 for 循环。除非有人建议使用更有效的方法。我认为没有必要对数据进行排序。另外,如果排序了,如何确定一步中是否有多个“highScore”案例。

最佳答案

除了您的 highScore 变量之外,您还创建了第二个变量,例如 std::list (或手动链表甚至小数组,具体取决于您可以使用的内容)。在此列表中,您可以跟踪实际拥有当前高分的人的指数。如果找到新的高分,则清除该列表并添加具有新高分的人。如果找到得分最高的人,您只需将他添加到列表中即可。

然后在循环之后你只需要打印这个列表中索引的玩家,而不是再次找出谁有高分。

关于C++压缩两个for循环提高效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12360179/

相关文章:

ios - 如何存储坐标 - iOS

javascript - 使用 javascript 连接两个变量并查找数组值位置

arrays - Nodejs S3删除多个对象错误

java - 共享空数组

c++ - 托盘图标不在 Visual c++ 中显示图像

c# - 设置和拆除单元测试上下文的概念的正确名称是什么?

头文件 LNK2019 中的 C++ API 实现

javascript - jQuery:打印嵌套数组中多个键的所有值

c++ - 在函数中返回 unsigned char 数组而不是指针

c++ - 有没有比 qsort 更快的排序程序?