Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created January 6, 2021 23:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/7491dd4261978a87b284d01f665d76ac to your computer and use it in GitHub Desktop.
Save parzibyte/7491dd4261978a87b284d01f665d76ac to your computer and use it in GitHub Desktop.
// https://parzibyte.me/blog
#include <iostream>
#include <array>
#include <map>
using namespace std;
int main()
{
// Declarar mapa
map<string, int> mapa;
// Vamos a contar cuántas veces se repite el lenguaje en la lista
// Esta lista podría venir de cualquier lugar
array<string, 16> lenguajes = {
"C",
"JavaScript",
"C++",
"C#",
"Python",
"PHP",
"Java",
"PHP",
"Python",
"PHP",
"PHP",
"Go",
"JavaScript",
"Python",
"JavaScript",
"Java",
};
// Recorrer el array
for (size_t i = 0; i < lenguajes.size(); i++)
{
string lenguajeActual = lenguajes.at(i);
cout << "Agregando " << lenguajeActual << " ... ";
// Si no existe, lo agregamos por primera vez
if (mapa.find(lenguajeActual) == mapa.end())
{
cout << "No existe. Se agrega por primera vez" << endl;
// Al inicio el conteo es 1
mapa[lenguajeActual] = 1;
}
else
{
// En caso de que ya exista
cout << "Ya existe. Se aumenta su conteo" << endl;
mapa[lenguajeActual]++;
}
}
// Ya hemos contado las palabras. Momento de recorrer e imprimir
map<string, int>::iterator iterador;
for (iterador = mapa.begin(); iterador != mapa.end(); iterador++)
{
// "first" tiene la clave. "second" el valor
string lenguaje = iterador->first;
int conteo = iterador->second;
cout << "El lenguaje " << lenguaje << " aparece " << conteo << " veces" << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment