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
| #include <vector> #include <string> #include <algorithm> #include <stdio.h> class foobar { public: std::string token; std::string item; int number; // 重载操作符 bool operator<(const foobar& rhs) { return (*this).token < rhs.token;}; bool operator>(const foobar& rhs) { return (*this).token > rhs.token;}; bool operator==(const foobar& rhs) { return (*this).token == rhs.token;} }; int struct_element_sort(int argc, char* argv[]) { std::vector<foobar> vFo1o; std::vector<foobar> vFoo = { {"osd_1", "OSD111", 1}, {"osd_0", "OSD000", 0}, {"osd_2", "OSD222", 2}, {"osd_4", "OSD444", 4}, {"osd_3", "OSD333", 3}, {"osd_1", "OSD100100", 100}, }; printf("before sort: \n"); for (auto& val : vFoo) { printf("token: %s font: %d item: %s\n", val.token.c_str(), val.number, val.item.c_str()); } // lambda表达式,升序 std::sort(vFoo.begin(),vFoo.end(), [](const foobar& s1, const foobar& s2) { return s1.token.compare(s2.token) < 0; }); printf("after sort--: \n"); for (auto& val : vFoo) { printf("token: %s font: %d item: %s\n", val.token.c_str(), val.number, val.item.c_str()); } std::vector<foobar>::iterator unque_it = std::unique(vFoo.begin(), vFoo.end()); vFoo.erase(unque_it, vFoo.end()); printf("after unque: \n"); for (auto& val : vFoo) { printf("token: %s font: %d item: %s\n", val.token.c_str(), val.number, val.item.c_str()); } return 0; }
|