Start learning free

LESSON 189 OF 409 · NESTED LOOPS

Top K Brands V5 - Filter by Product in C++

Practice

The full catalog covers many products. Filter to one product first, then rank the top k brands that sell it, using v4's repeated search on the filtered lists.

You start with:

vector<string> products = {"Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"};
vector<string> brands = {"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"};
vector<int> ratings = {4, 5, 5, 3, 4, 4};
string target = "Laptop";
int k = 2;

Build:

1. NeoByte (5)
2. TechPro (4)

Rules:

  • Filter: copy the brand and the rating of every row whose product equals target into two new lists, keeping the order.
  • From the filtered lists pick the top k by rating, highest first, with v4's repeated search. Ties go to the entry listed first.
  • If fewer than k products match, list only those that exist: when no brand is left, add no more lines (no extra lines, no error).
  • Each line is "rank. Brand (rating)", starting at rank 1.
  • Print the lines, one per line, with cout << ... << endl.

Build filteredBrands and filteredRatings first: a loop over the catalog that copies the row when products[i] == target.

Then run v4's repeated search over the filtered lists (same code, new names).

If fewer than k products match, some round finds nobody (bestIndex stays -1): add a line only when a brand was found.

vector<string> products = {"Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"};
vector<string> brands = {"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"};
vector<int> ratings = {4, 5, 5, 3, 4, 4};
string target = "Laptop";
int k = 2;

vector<string> filteredBrands;
vector<int> filteredRatings;
for (int i = 0; i < (int)products.size(); i++) {
    if (products[i] == target) {
        filteredBrands.push_back(brands[i]);
        filteredRatings.push_back(ratings[i]);
    }
}
vector<bool> used(filteredRatings.size(), false);
vector<string> lines;
for (int rank = 1; rank <= k; rank++) {
    int bestIndex = -1;
    for (int i = 0; i < (int)filteredRatings.size(); i++) {
        if (!used[i]) {
            if (bestIndex == -1 || filteredRatings[i] > filteredRatings[bestIndex]) {
                bestIndex = i;
            }
        }
    }
    if (bestIndex != -1) {
        used[bestIndex] = true;
        lines.push_back(to_string(rank) + ". " + filteredBrands[bestIndex] + " (" + to_string(filteredRatings[bestIndex]) + ")");
    }
}
for (int i = 0; i < (int)lines.size(); i++) cout << lines[i] << endl;

STEP 1 OF 18
    Ctrl + Enter to check

    Top K Brands V5 in C++

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free