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 65 66 67 68 69 70 71 72 73 74 75 76 77
|
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
//===============================================
void fromDateString( string text, int &day, int &month, int &year ) // Change dd.mm.yyyy to integers
{
day = stoi( text.substr( 0, 2 ) );
month = stoi( text.substr( 3, 2 ) );
year = stoi( text.substr( 6, 4 ) );
}
//===============================================
struct MyData
{
int year;
int month;
int day;
double value; // Change the type etc. as necessary
MyData( int y, int m, int d, double v ) : year( y ), month( m ), day( d ), value( v ) {} // Construct from individual values
MyData( string text, double v ) { fromDateString( text, day, month, year ); value = v; } // Construct from dd.mm.yyyy value
};
//===============================================
bool lessDate( MyData a, MyData b ) // Comparison of dates
{
return 10000 * ( a.year - b.year ) + 100 * ( a.month - b.month ) + ( a.day - b.day ) < 0;
}
//===============================================
bool lessValue( MyData a, MyData b ) // Comparison of values
{
return a.value < b.value;
}
//===============================================
ostream &operator<<( ostream &strm, MyData a ) // Output (insertion) operator for struct MyData
{
return strm << a.year << setw( 3 ) << a.month << setw( 3 ) << a.day << " " << a.value;
}
//===============================================
int main()
{
// Alternative input formats
// vector<MyData> dataset = { { 2010, 12, 31, 5.5 }, // You would probably read from file
// { 2012, 4, 20, 6.8 },
// { 2015, 1, 15, 3.2 },
// { 2011, 5, 10, 9.6 },
// { 1998, 1, 1, 7.2 } };
vector<MyData> dataset = { { "31.12.2010", 5.5 },
{ "20.04.2012", 6.8 },
{ "15.01.2015", 3.2 },
{ "10.05.2011", 9.6 },
{ "01.01.1998", 7.2 } };
cout << "\nSort by date:\n";
sort( dataset.begin(), dataset.end(), lessDate );
for ( auto x : dataset ) cout << x << endl;
cout << "\nSort by value:\n";
sort( dataset.begin(), dataset.end(), lessValue );
for ( auto x : dataset ) cout << x << endl;
}
//===============================================
|