How to flatten a 2D vector into a sorted one-dimensional vector in C++

2 Answers

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

int main() {
    std::vector<std::vector<int>> array2d = {
        {4, 5, 3},
        {30, 20},
        {10},
        {1, 2, 6, 7, 8},
    };

    std::vector<int> arr;

    for (const auto& row : array2d) {
        arr.insert(arr.end(), row.begin(), row.end());
    }

    std::sort(arr.begin(), arr.end());

    for (size_t i = 0; i < arr.size(); ++i) {
        if (i > 0) std::cout << ", ";
        std::cout << arr[i];
    }
}



/*
run:

1, 2, 3, 4, 5, 6, 7, 8, 10, 20, 30

*/

 



answered Aug 15, 2024 by avibootz
0 votes
#include <iostream>
#include <vector>
#include <algorithm>

// Flattens a 2D vector into a 1D vector and sorts it
std::vector<int> flattenAndSort(const std::vector<std::vector<int>>& array2d) {
    std::vector<int> result;

    // Insert all elements from each row into the result vector
    for (const auto& row : array2d) {
        result.insert(result.end(), row.begin(), row.end());
    }

    // Sort the flattened vector
    std::sort(result.begin(), result.end());

    return result;
}

int main() {
    std::vector<std::vector<int>> array2d = {
        {4, 5, 3},
        {30, 20},
        {10},
        {1, 2, 6, 7, 8},
    };

    std::vector<int> arr = flattenAndSort(array2d);

    // Print the sorted result
    for (size_t i = 0; i < arr.size(); ++i) {
        if (i > 0) std::cout << ", ";
        std::cout << arr[i];
    }
}


/*
run:

1, 2, 3, 4, 5, 6, 7, 8, 10, 20, 30

*/

 



answered 15 hours ago by avibootz
...