How to create a sorted unique vector from a matrix in C++

1 Answer

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

/*
    Create a sorted unique array (vec) from a matrix (vec of vec).
    The idiomatic approach uses:
      - std::set for uniqueness + automatic sorting
      - or std::vector + sort + unique for full control
*/

// Idiomatic using vector + sort + unique 
std::vector<int> make_sorted_unique_vec(const std::vector<std::vector<int>>& mat) {
    std::vector<int> vec;

    // Flatten matrix into vec
    for (const auto& slc : mat) {
        vec.insert(vec.end(), slc.begin(), slc.end());
    }

    // Sort
    std::sort(vec.begin(), vec.end());

    // Remove duplicates
    vec.erase(std::unique(vec.begin(), vec.end()), vec.end());

    return vec;
}

int main()
{
    std::vector<std::vector<int>> mat = {
        {5, 1, 17, 3, 8,  2,  1, 9},
        {3, 5,  7, 4, 2,  3,  4, 1},
        {9, 1,  8, 2, 3, 88, 17, 5}
    };

    auto vec = make_sorted_unique_vec(mat);

    for (int x : vec) std::cout << x << " ";
}



/* 
run:

1 2 3 4 5 7 8 9 17 88 

*/

 



answered May 6 by avibootz
...