Foncteur d'additionnement de std::pair
Bonjour,
Je suis actuellement en train de développer une classe qui analyse un flux entrant et compte le nombre d'occurrences pour chaque caractère, en stockant le résultat dans un std::map. Jusque là tout va bien, mais à la fin du programme je dois afficher le pourcentage d'occurrence pour chaque lettre, donc il me faut le nombre total de lettres qui ont été analysées, j'ai donc opté pour un foncteur :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| template<class T1, class T2>
class TotalPair
{
T2 m_total;
public:
void operator()(std::pair<T1, T2> const &x)
{
// Add number of occurrences
m_total += x.second;
}
T2 total() const
{
// Return total number of occurrences
return m_total;
}
TotalPair() : m_total(0)
{
}
}; |
Si j'affiche m_total depuis l'intérieur de la classe, tout fonctionne comme prévue, mais dès que je l'affiche depuis l'extérieur de la classe avec la méthode accesseur il m'affiche la valeur avec laquelle a été initialisée m_total :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| ostream &operator<<(ostream &out, FrequencyAnalysis const &freqAnalysis)
{
// Check output stream
if (not out)
throw runtime_error("operator<<: bad out");
// Get the total number of occurrences
statsMap stats(freqAnalysis.stats());
TotalPair<char, int> total;
for_each(stats.begin(), stats.end(), total);
cout << total.total() << endl; // FIXME: AFFICHE 0
// Print number of occurrences for each character
PrintPair<char, int> print(out);
for_each(stats.begin(), stats.end(), print);
// Return output stream
return out;
} |
Bref je ne vois vraiment pas d'où peut bien venir le problème, j'ai cherché pendant des heures, j'ai même essayé des exemples de code tout faits et censés fonctionner mais j'ai le même problème partout.
Merci par avance de votre aide,
Fr3ak.
Edit : mea culpa, je n'avais pas assez cherché, il fallait récupérer le retour de la fonction std::for_each.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| ostream &operator<<(ostream &out, FrequencyAnalysis const &freqAnalysis)
{
// Check output stream
if (not out)
throw runtime_error("operator<<: bad out");
// Get the total number of occurrences
statsMap stats(freqAnalysis.stats());
TotalPair<char, int> total;
total = for_each(stats.begin(), stats.end(), total);
cout << total.total() << endl; // OK
// Print number of occurrences for each character
PrintPair<char, int> print(out);
for_each(stats.begin(), stats.end(), print);
// Return output stream
return out;
} |