This is an old revision of the document!
Nous considérons la fonction suivante que nous ajoutons à l’espace de nom generic
.
Expliquez ce qu’elle fait et tester là.
#include <stdio.h> #include <random> .... template<> void populate_with_randoms(std::vector<std::string>& theVector, int theNumberOfValues, int theMinValue, int theMaxValue) { // Initialise le générateur de nombres aléatoires // et définit la loi de distribution uniforme. std::random_device rd; std::mt19937 generator(rd()) std::uniform_int_distribution<int> distribution(theMinValue, theMaxValue); char buffer[20]; int width = theMaxValue - theMinValue; for(; theNumberOfValues > 0; theNumberOfValues--) { int randValue = distribution(generator); std::sprintf(buffer,"%d",randValue); std::string stringValue = buffer; theVector.push_back(stringValue); } }
Nous souhaitons pouvoir choisir la fonction de comparaison utilisée dans le simple_sort
. Pour l’instant, la fonction de comparaison fait toujours appel à l’opérateur >
.
Nous souhaitons utiliser une classe traits
qui fournira l’opération de comparaison. Par défaut, cette opération de comparaison est >
.
Ecrire la classe greater_traits
en complétant ce qui manque dans la classe suivante:
template<typename T> struct greater_traits { public: static bool is_greater(T aValue, T anotherValue) { ... } };
Modifier la fonction simple_sort
pour qu’elle prenne un paramètre de type supplémentaire
qui est la classe fournissant l’opération de comparaison.
Proposer une classe lower_traits
qui inverse l’ordre de tri.
Tester votre code sur l’exemple suivant :
#include"generic_sort.hpp" #include<iostream> int main() { std::vector<int> array; generic::populate_with_randoms(array, 10, 1, 10); generic::print_vector(array); std::cout << "\n"; generic::simple_sort(array); generic::print_vector(array); std::cout << "\n"; generic::simple_sort<int, generic::lower_traits<int>>(array); generic::print_vector(array); return 0; }