Start learning free

LESSON 183 OF 281 · LOOPING OVER ARRAY INDICES

Top K Brands V3 in C++: Scanning Parallel Vectors for the Best

Practice Read the full explanation

Many brands sell the same product, stored in two parallel vectors: ratings[i] is the rating of brands[i]. Find the highest-rated brand by scanning with a loop.

You start with:

vector<string> brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
vector<int> ratings = {4, 5, 3, 5, 4};

Build:

1. MegaCorp (5)

Rules:

  • Keep the position of the best brand so far in bestIndex, starting at 0, and scan the positions from 1 to the end with a loop.
  • Update bestIndex only on a strictly higher rating. If two brands share the top rating, the one listed first wins (MegaCorp at position 1, not NeoByte at position 3).
  • Format the winner as "1. Brand (rating)" and print it with cout << ... << endl.

Walk the positions with for (int i = 1; i < (int)ratings.size(); i++) { and compare each rating with the best one so far.

C++ needs to_string(...) to join a number to a string with +.

vector<string> brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
vector<int> ratings = {4, 5, 3, 5, 4};

int bestIndex = 0;
for (int i = 1; i < (int)ratings.size(); i++) {
    if (ratings[i] > ratings[bestIndex]) {
        bestIndex = i;
    }
}
cout << "1. " << brands[bestIndex] << " (" << ratings[bestIndex] << ")" << endl;

STEP 1 OF 5
    Ctrl + Enter to check

    C++ · LOOPING OVER ARRAY INDICES

    Top K Brands V3 in C++, explained

    Problem overview

    Many brands now sell the same product. They live in two parallel vectors: brands holds the names and ratings holds the ratings, so ratings[i] belongs to brands[i]. The program finds the highest-rated brand with a loop and prints it as 1. Brand (rating). If several brands share the top rating, the one listed first wins.

    The starter data has ratings 4, 5, 3, 5 and 4. Two brands, MegaCorp and NeoByte, both have 5, and MegaCorp comes first, so the output is:

    1. MegaCorp (5)
    

    The previous version compared exactly two brands with if/else. A vector can hold any number of brands, so the comparison moves into a loop.

    Approach: keep the position of the best so far

    Start by assuming the brand at position 0 is the best. Then look at the remaining positions one by one, and whenever a brand's rating beats the best so far, make that brand the new best.

    The variable to keep is the position, bestIndex, not the rating. A position gives you both the name and the rating, because both vectors use the same index. If you stored only the rating, you could print the number but not whose it is.

    The comparison is strictly greater. When a later brand ties with the current best, the current best stays, which is the tie rule from the statement: MegaCorp at position 1 is not replaced by NeoByte at position 3, which has the same rating.

    Step by step

    1. Create bestIndex at 0. For now the first brand is the best.
    2. Write the loop. The int i starts at 1 and the loop runs while i < (int)ratings.size(). It starts at 1 because position 0 is already the best so far. The (int) cast makes the size a signed number so that both sides of the comparison are int.
    3. Compare inside the loop. An if checks whether ratings[i] is strictly greater than ratings[bestIndex].
    4. Update the position. Inside the if, set bestIndex to i.
    5. Print the winner after the loop, using brands[bestIndex] and ratings[bestIndex] in the 1. Brand (rating) format.

    The solution in C++

    vector<string> brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
    vector<int> ratings = {4, 5, 3, 5, 4};
    
    int bestIndex = 0;
    for (int i = 1; i < (int)ratings.size(); i++) {
        if (ratings[i] > ratings[bestIndex]) {
            bestIndex = i;
        }
    }
    cout << "1. " << brands[bestIndex] << " (" << ratings[bestIndex] << ")" << endl;
    

    Details worth a closer look:

    • The cast. ratings.size() is unsigned. Comparing it with the signed i produces a warning, and the cast avoids it.
    • Tracing the starter data. bestIndex starts at 0 with rating 4. At i = 1, the rating 5 beats 4, so bestIndex becomes 1. At i = 2, 3 does not beat 5. At i = 3, 5 does not beat 5, so bestIndex stays 1. At i = 4, 4 does not beat 5. The scan ends with bestIndex at 1, which is MegaCorp.
    • Printing numbers. The cout chain prints ratings[bestIndex] directly, so no to_string is needed in the final print.

    Complexity

    The loop looks at each brand once, so the time is O(n) for n brands. Only bestIndex and i are stored besides the input, so the extra space is O(1).

    Edge cases and common mistakes

    • Ties. With brands A, B, C and ratings 2, 2, 2, nothing is strictly greater, so bestIndex stays 0 and the output is 1. A (2). Using >= would end at the last brand instead.
    • The best brand last. With ratings 1, 2, 3, the loop updates twice and the output is 1. C (3).
    • One brand. The loop starts at 1 with a size of 1, so it never runs and the only brand is printed: 1. Solo (3).
    • An empty vector. brands[0] would be out of range, which is undefined behaviour. The lesson's data is never empty, but a general version should check first.
    • Storing the best rating only. The brand's name would be lost.
    • Starting the loop at 0. It works, because comparing position 0 with itself is never strictly greater, but it does one pointless comparison.
    • Mismatched vectors. The scan uses ratings.size() as the bound, so if brands were shorter, brands[bestIndex] could read out of range. The program relies on both vectors having the same length.

    Testing

    InputOutput
    the starter data1. MegaCorp (5)
    A, B, C with ratings 2, 2, 21. A (2)
    A, B, C with ratings 1, 2, 31. C (3)
    Solo with rating 31. Solo (3)
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free