【发布时间】:2020-04-24 17:34:03
【问题描述】:
如果失败,如何根据其成员数据对结构/类数组进行排序?
#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);
}
gcc 给出:
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);
^~~~~
感谢真诚有用的帮助
【问题讨论】:
-
这能回答你的问题吗? How can I sort the array of class?
-
您的实际问题是,
m是一个O[],它没有任何功能。使用std::vector。 (您尝试在O[]上调用.begin())并在您的排序函数中比较字符串数组。你想比较两个字符串吗? -
C 样式数组没有
begin()和end()成员。请改用std::begin()和std::end()(或std::array)。 -
@churill 或使用
std::begin()和std::end(),它们适用于固定数组。但是代码仍然会失败,因为a.n < b.n没有为string[]数组定义。而且,bfunction()需要通过引用来获取它的参数
标签: c++ arrays algorithm class sorting