通过返回指向映射的指针 C++ 来访问映射

accessing a map by returning a pointer to it c++

本文关键字:映射 指针 C++ 访问 返回      更新时间:2023-10-16

我正在尝试在一个返回指向映射的常量指针的类中创建一个函数。然后在不同的类中,我可以有一个函数,它可以接受常量指针,声明迭代器,并将映射的内容复制到向量中。此映射类到向量类是练习的要求。我以前从未做过 ptrs 到地图,也没有编译器喜欢的语法。这是我在 Map 中的函数声明:

class WordCount
{
    public:
        WordCount();
        ~WordCount();
        void word_insert(std::string clean_word);
        void print_all();
        const std::map<std::string, int> * get_map();
    private:
        std::map<std::string, int> m_word_counts;
        std::map<std::string, int>::iterator m_it;
        std::pair<std::map<std::string, int>::iterator, bool> m_ret; 
};

但是当我尝试这样定义函数(或我尝试过的许多变体)时,我得到一个转换错误。以下需要更改哪些内容?

const map<string, int > * WordCount::get_map()
{
    const map<string, int > *ptr = m_word_counts;
    return ptr;
}

--

我只会返回一个引用。

const map<string, int > & WordCount::get_map()
{
    const map<string, int > &ptr = m_word_counts;
    return ptr;
}
const map<string, int > *ptr = &m_word_counts;