You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用std::sort对std::array进行排序?

问题原因

原生数组名会隐式转换为指向第一个元素的指针,所以nums + 5能合法得到尾后指针;但std::array是封装后的容器类,它本身没有重载operator+,直接用morenums + 5会触发编译错误,同时std::sort找不到匹配的重载(因为参数类型不匹配)。

解决方法

std::sort接受迭代器作为参数,std::array提供了成员函数begin()和end()来获取首尾迭代器,也可以使用全局的std::begin()和std::end()函数,两种方式都能让std::sort正确工作。

修正后的代码示例

#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); // 原生数组写法不变
    // 方法1:使用std::array的成员迭代器
    std::sort(morenums.begin(), morenums.end());
    // 方法2:使用全局std::begin/std::end
    // std::sort(std::begin(morenums), std::end(morenums));
}

额外说明

如果需要排序std::array的部分元素(比如前3个元素),可以利用std::array迭代器的随机访问特性,用begin()加偏移量的方式指定范围:

std::sort(morenums.begin(), morenums.begin() + 3);

内容的提问来源于stack exchange,提问作者all_caps

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 15:37:10