Search code examples
c++sortingstdarray

How to use std::sort with an std::array?


I need to sort an std::array, but I can't figure out how to do that using the std::sort() function, since I get the errors "no instance of overloaded function sort matches the argument list" and "no operator '+' matches these operands". When I use the same syntax to try to sort a regular array, I have no errors. Here is code which produces the problem:

#include <algorithm>
#include <array>

int nums[5] = {1, 2, 3, 4, 5};
std::array<int, 5> morenums = {1, 2, 3, 4, 5};


int main(){
    std::sort(nums, nums + 5);//no error
    std::sort(morenums, morenums + 5);//error    
}

I was trying to use the std::sort() method to sort an std::array, but I couldn't figure out how to do this, since I kept getting errors.


Solution

  • Same as you would sort any other container, such as std::vector:

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

    It's the plain arrays that have the odd syntax, not std::array.

    You can also do std::sort(std::begin(morenums), std::end(morenums)); or std::ranges::sort(morenums);, those work for both plain arrays and containers.