How to sort an array of struct/class based on its member data, as this fails ?
#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 gives:
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);
^~~~~
sincere useful help is appreciated
mis anO[]which has no functions whatsoever. Usestd::vector. (You try to call.begin()on anO[]) And in your sort function you compare arrays of string. Did you want to compare two strings?begin()andend()members. Usestd::begin()andstd::end()instead (orstd::array).std::begin()andstd::end(), which work with fixed arrays. But then the code will still fail sincea.n < b.nis not defined forstring[]arrays. And also,bfunction()needs to take its parameters by reference