• Viernes 17 de Mayo de 2024, 01:35

Autor Tema:  Como se utiliza Función Objeto? :( Es importante porfavor !!  (Leído 826 veces)

Phass

  • Nuevo Miembro
  • *
  • Mensajes: 13
    • Ver Perfil
Como se utiliza Función Objeto? :( Es importante porfavor !!
« en: Miércoles 23 de Junio de 2010, 13:47 »
0
Hola, necesito hacer una práctica para aprobar una asignatura de la carrera en la que me piden usar una función objeto. Yo tengo el código siguiente:

Código: C++
  1. #include <iostream>
  2. #include <vector>
  3. #include <iterator>
  4. #include <algorithm>
  5. #include <map>
  6.  
  7. using namespace std;
  8.  
  9. map<string,int> d;
  10.  
  11. void mifuncion (pair<string, string> t)
  12. {
  13.   map<string, int>::iterator i;
  14.   i = d.find(t.first);
  15.   if (i != d.end()) // Existe clave
  16.     d[t.first] += 1;
  17.   else
  18.       d.insert(i, pair<string,int>(t.first,1));
  19. }
  20.  
  21.  
  22. int main ()
  23. {
  24.         multimap<string, string> multi;
  25.  
  26.         cout << "Vaya insertando las claves en la forma K1, K2" << endl;
  27.         cout << "Presione ctrl+z para finalizar" << endl;
  28.  
  29.         string k1, k2;
  30.  
  31.         while (cin >> k1)
  32.         {
  33.             cin >> k2;
  34.             multi.insert(pair<string, string>(k1, k2));
  35.         }
  36.  
  37.         cout << endl << "Elementos del multidiccionario: " << endl;
  38.         for (multimap<string, string>::iterator it = multi.begin(); it != multi.end(); ++it)
  39.            {
  40.                cout << "  [" << (*it).first << ", " << (*it).second << "]" << endl;
  41.            }
  42.  
  43.         for_each (multi.begin(), multi.end(), mifuncion);
  44.  
  45.         cout << endl << "Elementos del diccionario: " << endl;
  46.         for (map<string, int>::iterator it = d.begin(); it != d.end(); ++it)
  47.            {
  48.                cout << "  [" << (*it).first << ", " << (*it).second << "]" << endl;
  49.            }
  50.  
  51.         return 0;
  52. }
  53.  


Cómo es entonces haciéndolo con una función objeto sin necesidad de declarar el diccionario global?

Muchas gracias !!

Amilius

  • Miembro HIPER activo
  • ****
  • Mensajes: 665
    • Ver Perfil
Re: Como se utiliza Función Objeto? :( Es importante porfavor !!
« Respuesta #1 en: Jueves 24 de Junio de 2010, 01:33 »
0
Como el objeto función sólo tendría que tener un parámetro para que funcione con "for_each()" podrías crear un par que contenga el par del tipo requerido por el mapa y una referencia al mapa que quieres usar.