How do I remove duplicates with std::array?

When working with `std::array` in C++, you may encounter situations where you need to remove duplicate elements. Here’s how you can do this effectively using standard algorithms.

C++, std::array, remove duplicates, standard algorithms, programming tips
This guide demonstrates how to remove duplicates from a std::array in C++ using standard algorithms for efficient data management.

#include <iostream>
#include <array>
#include <algorithm>

int main() {
    std::array arr = {1, 2, 3, 2, 4, 5, 5, 1, 6, 7};
    
    // Sort the array
    std::sort(arr.begin(), arr.end());
    
    // Remove duplicates
    auto last = std::unique(arr.begin(), arr.end());
    
    // Resize the array to remove duplicates
    arr.resize(std::distance(arr.begin(), last));
    
    // Print the result
    std::cout << "Array after removing duplicates: ";
    for(auto a : arr) {
        std::cout << a << " ";
    }
    std::cout << std::endl;

    return 0;
}
    

C++ std::array remove duplicates standard algorithms programming tips