User Tools

Site Tools


in204:tds:sujets:td3:part2

This is an old revision of the document!


Partie II – Fonction spécialisée

TD3

Question n°1

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);
    }
}

Correction

Correction

Supposons d'abord que nous souhaitons appelé la fonction generic::populate_with_randoms en lui passant un tableau de type std::string avec le code suivant :

#include <iostream>
#include"simple_sort.hpp"
#include<string>
 
using namespace std;
 
int main()
{
    {
        using namespace generic;
        std::vector<std::string> stringValues;
 
        populate_with_randoms(stringValues, 10, 'A', 'Z');
        print_vector(stringValues);
        simple_sort(stringValues);
        print_vector(stringValues);
    }
    return 0;

La compilation de ce code génère une erreur à la ligne :

namespace generic
{
    template<typename T, typename genType = int>
    void populate_with_randoms(
        std::vector<T>& theVector,
      	int theNumberOfValues, genType theMinValue, genType theMaxValue)
    {
        ...
        theVector.push_back(
            (T)distribution(gen));
    }
}

Question n°2

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 >.

Question n°2.1

Ecrire la classe greater_traits en complétant ce qui manque dans la classe suivante:

Correction

Correction

La classe greater_test teste si aValue > anotherValue et retourne true si la condition est vérifiée et false si cette condition n'est pas vérifiée.

template<typename T>
struct greater_traits
{
public:
    static bool is_greater(T aValue, T anotherValue) 
    {
        return aValue > anotherValue;
    }
};

La méthode is_greater est précédée du mot clé static, ce qui signifie que cette méthode est une méthode statique aussi appellée méthode de classe. A la différence des méthodes habituelles de l'objet, cette méthode ne peut accéder qu'aux champs statique statiques de la classe. En conséquence, cette méthode n'a pas besoin qu'un objet soit créé pour pouvoir être appelé. Elle peut simplement être appellée selon la syntaxe suivante :

int main()
{
    greater_traits<int>::is_greater(3, 2);
}

Question n°2.2

Modifier la fonction simple_sort pour qu’elle prenne un argument supplémentaire qui est la classe fournissant l’opération de comparaison.

Correction

Correction

namespace generic {

  ...

template<typename T, typename sortTraits = greater_traits<T»

  void simple_sort(std::vector<T>& theValues)
  {
      sortTraits sort_traits;
          // Initialise la classe comparateur.        
      int length = theValues.size();
      for(int i = 0; i < length-1; i ++)
      {
          for(int j= i+1; j < length; j++)
          {
              if(sort_traits.compare(theValues[i], theValues[j]) > 0)
                  std::swap(theValues[i], theValues[j]);
          }
      }
  }
  ...

}

Question n°2.3

Proposer une classe lower_traits qui inverse l’ordre de tri.

Question n°2.4

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;
}
in204/tds/sujets/td3/part2.1570282373.txt.gz · Last modified: 2019/10/05 13:32 by bmonsuez