Before writing a post, avoid repeating code--know your library. It's raining outside today, it's not a good mood, just come and complain =v=
Last week a company came here to recruit, the C + + version of the volume is said to be a request for a custom struct vector to do the sorting. Struct has two field, an int num, and a string name; Sorting requirements are in num ascending order, if Num is equal, in ascending name. What exactly is the original question I do not know, but it is said to be a naked struct, perhaps so?
C + + code
struct person {
int num;
string name;
};
Hmm ... I don't know if there is a constructor in the original question. Whatever it is. There is no overloaded < or = operator on top of it anyway. Also, listen to the students that the vector in the original question is an instance rather than a pointer, so the following code reflects this. I'm not trying to put a case into it, OTL.
So to sort. Well, I heard a group of students just finished getting back to the computer room in the discussion sort algorithm how to write and so on. But this is C + +, there is a standard library to solve this problem, do not have to do their own, is not it?
At a minimum, such as saying:
C + + code
#include <algorithm> #include <functional> #include <iostream> #include <string> #include <
Vector> using namespace std;
struct person {int num;
String name;
person (int num, string name): num (num), name (name) {}}; namespace Std {template<> struct less<person> {bool operator () (const person& P1, const
person& p2) {if (P1.num < p2.num) return true;
if (P1.num = = P2.num && p1.name < p2.name) return true;
return false;
}
}; } struct Printelement {void operator () (const person& p) {cout << "person:" << P.num <
< "," << p.name << Endl;
}
};
int main () {vector<person> V;
V.push_back (2, String ("Smith"));
V.push_back (1, String ("John"));
V.push_back (2, String ("Micheal"));
V.push_back (1, String ("Micheal")); V.push_back (3, String ("Albert"));
Sort (V.begin (), V.end (), less<person> ());
For_each (V.begin (), V.end (), printelement ()); //Output://Person:1, John/Person:1, Micheal//Person:2, micheal//Person:2, Smith//Person:3, Albert