1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
#include <ctime>
#include <string>
#include <vector>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <algorithm>
struct mystruct
{
int id;
std::string a;
std::string b;
};
bool sort_by_abc(const mystruct& lhs, const mystruct& rhs)
{
if(lhs.a == rhs.a)
{
return lhs.b < rhs.b;
}
return lhs.a < rhs.a;
}
int main()
{
// Initialise random numbers
std::srand(std::time(0));
mystruct m;
std::vector<mystruct> v;
std::vector<mystruct>::iterator i;
// Add random strings
std::string s = "abc";
for(int i = 0; i < 20; ++i)
{
m.id = i;
std::random_shuffle(s.begin(), s.end());
m.a = s;
std::random_shuffle(s.begin(), s.end());
m.b = s;
v.push_back(m);
}
std::cout << "Before the sort:\n";
for(i = v.begin(); i != v.end(); ++i)
{
std::cout << '\t' << std::setw(2) << i->id << ": ";
std::cout << i->a << ", " << i->b << '\n';
}
std::sort(v.begin(), v.end(), &sort_by_abc);
std::cout << "After the sort:\n";
for(i = v.begin(); i != v.end(); ++i)
{
std::cout << '\t' << std::setw(2) << i->id << ": ";
std::cout << i->a << ", " << i->b << '\n';
}
return 0;
}
|
Before the sort:
0: cab, bca
1: bca, cab
2: acb, bac
3: cba, cba
4: acb, abc
5: cba, cab
6: abc, cab
7: cab, acb
8: bac, acb
9: acb, abc
10: bac, cab
11: acb, cba
12: acb, cba
13: acb, cab
14: abc, cab
15: abc, acb
16: cba, bca
17: acb, bca
18: cba, cba
19: bac, bca
After the sort:
15: abc, acb
6: abc, cab
14: abc, cab
4: acb, abc
9: acb, abc
2: acb, bac
17: acb, bca
13: acb, cab
11: acb, cba
12: acb, cba
8: bac, acb
19: bac, bca
10: bac, cab
1: bca, cab
7: cab, acb
0: cab, bca
16: cba, bca
5: cba, cab
3: cba, cba
18: cba, cba |