I have the following code:
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <sstream>
using namespace std;
typedef std::map<std::string, std::shared_ptr<void>> M;
typedef std::vector<std::string> S;
void build_word_tree_from_sentences(const S& sentence_list, M& root)
{
for (const auto& sentence : sentence_list)
{
std::string word;
std::stringstream ss(sentence);
M* base = &root;
while (ss >> word)
{
auto found = base->find(word);
if (found == base->end())
{
base->insert(std::make_pair(word, std::make_shared<M>()));
}
auto b = base->find(word)->second;
base = std::static_pointer_cast<M>(b).get();
}
}
}
int main()
{
S sentence_list = {"Hello word", "Hello there"};
M tree;
build_word_tree_from_sentences(sentence_list, tree);
}
I would like to have a help in understanding the use of the shared_ptr in the map M. When inserting a new element, if not already present, in the map:
base->insert(std::make_pair(word, std::make_shared<M>()));
共有的买家用空话,这也使我感到困惑。