#include #include #include #include #include using namespace std; // With STL you use building blocks to create increasingly complicated // structures. Algorithms always treat the building block of the // container, however complicated. // A std::map is somewhat special, saying map actually create the // structure map> // Compare the solutions below. // The vector always contain rows, but a row is increasingly complex // and everything that deal with a row is adjusted accordingly. // The "using" declarations make later code clearer. // I've appended a single digit (1,2,3) to distinguish which solution // things belong to, or the compiler would complain about conflicting // types and several main functions. // Sorting uses a function pointer, printing a lambda, but either // choice is possible. // Example 1, simple rows using my_row1 = int; using my_data1 = vector; bool my_less1(my_row1 const& a, my_row1 const& b) { return a < b; } int main1() { my_data1 data; int a; while (cin >> a) { data.push_back( a ); } sort(data.begin(), data.end(), my_less1); for_each(data.cbegin(), data.cend(), [](my_row1 const& r)->void{ cout << setw(5) << r << endl; }); return 0; } // Example 2, tuple rows using my_row2 = tuple; using my_data2 = vector; bool my_less2(my_row2 const& a, my_row2 const& b) { // Sort by second int return get<1>(a) < get<1>(b); } int main2() { my_data2 data; int a, b, c; while (cin >> a >> b >> c) { data.push_back( make_tuple(a, b, c) ); } sort(data.begin(), data.end(), my_less2); for_each(data.cbegin(), data.cend(), [](my_row2 const& r)->void{ cout << setw(5) << get<0>(r) << setw(5) << get<1>(r) << setw(5) << get<2>(r) << endl; }); return 0; } // Example 3, complex rows using my_atom3 = tuple< int, int>; using my_row3 = tuple< my_atom3, int>; using my_data3 = vector; bool my_less3(my_row3 const& a, my_row3 const& b) { // Sort by second int in my_atom my_atom3 aa = get<0>(a); my_atom3 bb = get<0>(b); return get<1>(aa) < get<1>(bb); } int main3() { my_data3 data; int a, b, c; while (cin >> a >> b >> c) { data.push_back( make_tuple( make_tuple(a, b), c) ); } sort(data.begin(), data.end(), my_less3); for_each(data.cbegin(), data.cend(), [](my_row3 const& r)->void{ my_atom3 a = get<0>(r); cout << setw(5) << get<0>(a) << setw(5) << get<1>(a) << setw(5) << get<1>(r) << endl; }); return 0; } int main() { main1(); cin.clear(); main2(); cin.clear(); main3(); cin.clear(); return 0; }