Обновление Для хорошей меры добавлен пример на основе std :: map (см. Ниже)
Я бы не работал над сортировкой так же, как над структурами данных:)
Вот пример, который я написал, чтобы стереть пыль с моих навыков C ++ :) Извините, если я добавил больше, чем кухонная раковина.
Также обратите внимание, что для этого типа данных 'tivial' вы, вероятно, могли бы использовать std :: pair в качестве структуры 'Report' и std :: map в качестве типа контейнера, что требует значительно меньшего количества ручного кодирования, но я хотелпокажет вам, как все делается, если вы закодировали структуру вручную:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
static struct Report
{
int date;
double base;
Report(int d, double b) : date(d), base(b) {}
bool operator<(const Report& rhs) const
{
return (date<rhs.date) || ((date==rhs.date) && (base<rhs.base));
}
friend std::ostream& operator<<(std::ostream& os, const Report& r)
{
os << "Report(" << r.date << ", " << r.base << ")";
}
} theData[] = {
Report( 13, 42.3),
Report( 12, 42.5),
Report( 14, 42.8),
Report( 15, 43.1),
Report( 18, 43.1),
Report( 16, 43.4),
Report( 17, 43.8),
};
int main(int argc, const char* args[])
{
Report *const begin = theData;
Report *const end = theData+(sizeof(theData)/sizeof(*theData));
// simpler container, take a copy for comparison
std::vector<Report> simplerData(begin, end);
// just sort it
std::sort(begin, end);
// VERIFY by printing to console
std::cout << "Verify sorted array: " << std::endl;
std::copy(begin, end, std::ostream_iterator<Report>(std::cout, "\n"));
std::cout << "=====================" << std::endl;
std::cout << "Verify unsorted copy:" << std::endl;
std::copy(simplerData.begin(), simplerData.end(), std::ostream_iterator<Report>(std::cout, "\n"));
std::cout << "=====================" << std::endl;
// Sort that as well - for fun, reversed
std::sort(simplerData.begin(), simplerData.end(), std::not2(std::less<Report>()));
std::cout << "Verify reversed copy:" << std::endl;
std::copy(simplerData.begin(), simplerData.end(), std::ostream_iterator<Report>(std::cout, "\n"));
std::cout << "=====================" << std::endl;
}
Скомпилируйте и запустите, используя:
g++ -o test test.cpp
./test
Вывод:
Verify sorted array:
Report(12, 42.5)
Report(13, 42.3)
Report(14, 42.8)
Report(15, 43.1)
Report(16, 43.4)
Report(17, 43.8)
Report(18, 43.1)
=====================
Verify unsorted copy:
Report(13, 42.3)
Report(12, 42.5)
Report(14, 42.8)
Report(15, 43.1)
Report(18, 43.1)
Report(16, 43.4)
Report(17, 43.8)
=====================
Verify reversed copy:
Report(18, 43.1)
Report(17, 43.8)
Report(16, 43.4)
Report(15, 43.1)
Report(14, 42.8)
Report(13, 42.3)
Report(12, 42.5)
=====================
Для полноты, вот как это будет выглядеть при использовании std :: map, как я предложил выше.Обратите внимание, что упорядочение по ключам неявно:
namespace std // hacky, google Koenig lookup...
{
template <class K, class V> static std::ostream& operator<<(std::ostream& os, const std::pair<K, V> p)
{ os << "[" << p.first << ", " << p.second << "]"; }
}
void static UsingStdMap()
{
typedef std::map<int, double> Reports;
typedef Reports::value_type Report;
static const Report initializer[] = {Report(13,42.3),Report(12,42.5),Report(14,42.8),Report(15,43.1),Report(18,43.1),Report(16,43.4),Report(17,43.8)};
Reports theMap(initializer, initializer+sizeof(initializer)/sizeof(*initializer));
std::copy(theMap.begin(), theMap.end(), std::ostream_iterator<Report>(std::cout, "\n"));
}
Я упоминал, что я немного ленив?Отсюда и взлом для отображения элементов с помощью оператора потока.Чтобы использовать заказ, см. здесь , например