gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 20:07:02 24 4
gpt4 key购买 nike

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

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com