Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,683 questions

55,435 answers

573 users

How to find the N smallest values in a 2D vector in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <algorithm>

/*
    Find the N smallest values in a 2D vector.

    The program uses a two‑step approach:
    1. Flatten the 2D vector into a single vector.
    2. Use std::nth_element to partition the vector so that the first N
       elements are the smallest (in any order).
    3. Sort only those N elements for clean output.

    This avoids sorting the entire dataset and is efficient even for large inputs.
*/

// Flatten a 2D vector into a 1D vector
std::vector<int> flatten(const std::vector<std::vector<int>>& matrix) {
    std::vector<int> result;
    for (const auto& row : matrix) {
        result.insert(result.end(), row.begin(), row.end());
    }
    
    return result;
}

// Extract the N smallest values
std::vector<int> smallestN(const std::vector<std::vector<int>>& matrix, std::size_t N) {
    auto flat = flatten(matrix);

    if (N >= flat.size()) {
        std::sort(flat.begin(), flat.end());
        return flat;
    }

    // Partition so that the first N elements are the smallest
    std::nth_element(flat.begin(), flat.begin() + N, flat.end());

    // Sort only the smallest N elements
    std::vector<int> result(flat.begin(), flat.begin() + N);
    std::sort(result.begin(), result.end());

    return result;
}

int main() {
    std::vector<std::vector<int>> matrix = {
        {12, 5, 7},
        {3, 19, 1},
        {8, 4, 6}
    };

    std::size_t N = 5;

    auto values = smallestN(matrix, N);

    std::cout << "The " << N << " smallest values:\n";
    for (int v : values) {
        std::cout << v << " ";
    }
}



/*
run:

The 5 smallest values:
1 3 4 5 6 

*/

 



answered 3 days ago by avibootz
...