What is the standard practice of creating a map and returning it to a function as a reference?
In my example, I am just creating a hashmap of the character count from a string, and doing this twice. I see that to return it from the function, the map would have to be created dynamically, otherwise, it would go out of scope and lead to undefined behavior.
However, I don't know how to add to the map, with just a pointer to it. (see code map[*it] += 1;
), and I'm not sure if I'm going about the process in the correct way.
#include <iostream>
#include <map>
std::map<char, int>& createMap(std::string& myString){
std::map<char, int>* map = new std::map<char, int>();
for(std::string::iterator it = myString.begin(); it != myString.end(); ++it){
map[*it] += 1;
}
return map;
}
void turnStringsIntoMaps(std::string a, std::string b){
std::map<char, int> firstMap = createMap(a);
std::map<char, int> secondMap = createMap(b);
for(auto it = m.begin(); it != m.end(); ++it){
std::cout << it->first << " : " << it->second << '\n';
std::cout << m[it->first] << '\n';
}
return true;
}