I'm looking for the most simple and efficient way to track the number of string elements in a container.
Previously, I used std::vector
but I tried changing the container to std::unordered_map
since I hear that it can be easier and more performant for my use.
My Code :
#include <iostream>
#include <string>
#include <unordered_map>
class Table
{
public:
void insert(const std::string &name)
{
auto it = data.find(name);
if (it == data.end())
{
data[name] = 1;
return;
}
data[name]++;
}
void remove(const std::string &name)
{
auto it = data.find(name);
if (it == data.end())
return;
if (--data[name] == 0)
data.erase(it);
}
/* get the number of occurrences */
int count(const std::string &name)
{
auto it = data.find(name);
if (it == data.end())
return 0;
return data[name];
}
private:
std::unordered_map<std::string, int> data;
};
int main()
{
Table table;
table.insert("Apple");
table.insert("Apple");
table.insert("Orange");
table.insert("Orange");
table.remove("Orange");
std::cout << "Number of Apples : " << table.count("Apple") << std::endl;
std::cout << "Number of Oranges : " << table.count("Orange") << std::endl;
std::cout << "Number of Lemons : " << table.count("Lemon") << std::endl;
}
The Result :
Number of Apples : 2
Number of Oranges : 1
Number of Lemons : 0
Program ended with exit code: 0
Is there a way to improve the class Table
so my program can be more efficient than now?
The program seems to work but I used std::unordered_map
for the first time so I'm not really sure if my implementation is correctly done.