Skip to content

Instantly share code, notes, and snippets.

@saulozitos
Last active July 26, 2021 17:03
Show Gist options
  • Save saulozitos/ded2836adf342ce93567d4266e796440 to your computer and use it in GitHub Desktop.
Save saulozitos/ded2836adf342ce93567d4266e796440 to your computer and use it in GitHub Desktop.
Storing std::unique_ptr in a std::map
#include <array>
#include <iostream>
#include <map>
#include <memory>
#include <string>
namespace Global {
const std::array<std::string, 20> namesArray {
"Kiesha",
"Ashlee",
"Lawana",
"Jesica",
"Manie",
"Twyla",
"Fredric",
"Nick",
"Tuan",
"Herminia",
"Jillian",
"Aldo",
"Doretta",
"Ike",
"Krystin",
"Louann",
"Roseann",
"Carlee",
"Eleanor",
"Melania"
};
} // Global namespace
struct Names {
Names(std::string n)
: m_name(std::move(n))
{
std::cout << "Constructor! " << m_name << "\n";
}
~Names()
{
std::cout << "Destructor! " << m_name << "\n";
}
std::string m_name;
};
struct Manager {
void add(const std::string& n)
{
m_map.emplace(n, new Names(n));
}
void remove(const std::string& name)
{
m_map.erase(name);
}
bool keyExists(const std::string &key)
{
return m_map.find(key) != m_map.end();
}
std::map<std::string, std::unique_ptr<Names>> m_map;
};
int main()
{
Manager m;
std::cout << "Populating Names object in map.\n";
for (const auto& name : Global::namesArray) {
m.add(name);
}
std::cout << "\nPrinting map.\n";
for (const auto& it : m.m_map) {
std::cout << it.first << " - " << it.second->m_name << "\n";
}
std::cout << "\nDeleting the first 10 names from the map.\n";
for (auto position = 0; position < 10; ++position) {
m.remove(Global::namesArray.at(position));
}
std::cout << "\nPrinting map.\n";
for (const auto& it : m.m_map) {
std::cout << it.first << " - " << it.second->m_name << "\n";
}
return 0;
}
@saulozitos
Copy link
Author

saulozitos commented Jul 26, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment