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

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

本文关键字:std 排序 array sort 何使用      更新时间:2023-10-16
#include <iostream>
#include <array>
#include <algorithm>
#include <cstring>
using namespace std;
int main() {
    array<char, 20> test{"HelloWorld"}, tmp;
    // method 1
    tmp = test;
    sort(tmp.begin(), tmp.begin() + strlen(tmp.begin()));
    cout << "result: " << tmp.data() << endl;
    // method 2
    tmp = test;
    sort(tmp.begin(), tmp.end());
    cout << "result: " << tmp.data() << endl;
    return 0;
}

std::array可以使用方法 1 进行排序。但它太丑了。

我更喜欢方法 2,但什么都不能返回。怎么了?

第二种方法是将所有元素排序到前面。 (它们任何其他字符都少。

当您尝试使用.data()打印它时,您会得到一个char const*对象,该对象在流类中被视为 C 字符串。这是一个以空结尾的字符串。由于第一个字符为空,因此它不打印任何内容。

你可以用

    auto cmp = [](char a, char b) { return a != '' && a<b; }
    sort(tmp.begin(), tmp.end(), cmp);

这使用一个比较器,该比较器在最后对进行排序。

但正如杰里·科芬(Jerry Coffin(在评论中所说,std::array并不std::string - 使用适合您需求的那个(在这种情况下可能std::string(。

您正在打印一个 C 字符串,它依赖于终止空字符的存在:
对整个数组进行排序时,将该空字符移到前面,这会告知打印函数它是一个空字符串。

因此,您别无选择,只能使用更丑陋的版本。 话虽如此,这里有一种更安全的编写方法,您可能更喜欢:

sort(tmp.begin(), find(tmp.begin(), tmp.end(), ''));