c++ - 如何根据其成员数据对结构/类数组进行排序?

标签 c++ arrays algorithm class sorting

如何根据其成员数据对结构/类数组进行排序,因为这会失败?

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;                                          

struct O{
    const string n;
    int a=1;
};

bool bfunction (O a, O b) {
    return a.n < b.n; }

int main () {

    O m[]={ {"unta"}, {"jalan"}, {"sama"}, {"aki"} };


// using function in sort control
    sort (m.begin(), m.end(), &bfunction);
}

海湾合作委员会给出:

 error: request for member ‘begin’ in ‘m’, which is of non-class type ‘O [4]’
     sort (m.begin(), m.end(), &bfunction);
             ^~~~~
 error: request for member ‘end’ in ‘m’, which is of non-class type ‘O [4]’
     sort (m.begin(), m.end(), &bfunction);
                        ^~~~~

感谢真诚有用的帮助

最佳答案

使用std::array

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

struct O {
    std::string n;
    int a;

    O(const char* c) : a(1) { n = c; }
};

bool bfunction(O a, O b) {
    return a.n < b.n;
}

int main() {
    std::array<O, 4> m = { "unta", "jalan", "sama", "aki" };

    // using function in sort control
    std::sort(m.begin(), m.end(), &bfunction);
}

关于c++ - 如何根据其成员数据对结构/类数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59624556/

相关文章:

c++ - 如何在所有尺寸下使这项工作(c++ 初学者文件输入)

c++ - 在 Bazel 中移动文件

c - 在 C 中定义一个全局结构指针?

arrays - 在 Swift 5 中将字节数组转换为 Int64

php - 打印级联表

c++ - 使用 Nginx HTTP 解析器的 API

c++ - 如何告诉 g++ 编译器在哪里搜索包含文件?

C++ 返回一个数组

algorithm - TAOCP中的不相交集

algorithm - 如何在任意四边形内刻上一个矩形或圆形